乐闻世界logo
搜索文章和话题

How to implement template rendering and static file serving in the Gin framework?

2月21日 15:19

Template rendering and static file serving in the Gin framework are as follows:

1. Template rendering

Gin supports multiple template engines, including HTML, Pug, Ace, etc.

1.1 Loading templates

go
import "github.com/gin-gonic/gin" func main() { r := gin.Default() // Load template files r.LoadHTMLGlob("templates/*") // Or load specific templates r.LoadHTMLFiles("templates/index.html", "templates/about.html") r.Run(":8080") }

1.2 Rendering HTML templates

go
func renderHTML(c *gin.Context) { c.HTML(200, "index.html", gin.H{ "title": "Home Page", "message": "Welcome to Gin!", }) }

1.3 Template inheritance

go
// Base template templates/base.html <!DOCTYPE html> <html> <head> <title>{{ .title }}</title> </head> <body> {{ block "content" . }}{{ end }} </body> </html> // Child template templates/index.html {{ define "content" }} <h1>{{ .message }}</h1> {{ end }} // Render inherited template func renderInherited(c *gin.Context) { c.HTML(200, "index.html", gin.H{ "title": "Home", "message": "Welcome!", }) }

1.4 Custom template functions

go
func main() { r := gin.Default() // Create template engine t := template.Must(template.New("").Funcs(template.FuncMap{ "upper": strings.ToUpper, "formatDate": func(t time.Time) string { return t.Format("2006-01-02") }, }).ParseGlob("templates/*")) // Set custom template engine r.SetHTMLTemplate(t) r.GET("/", func(c *gin.Context) { c.HTML(200, "index.html", gin.H{ "name": "john", "date": time.Now(), }) }) r.Run(":8080") }

2. Static file serving

2.1 Basic static file serving

go
func main() { r := gin.Default() // Provide static file service r.Static("/static", "./static") // Or r.Static("/assets", "./assets") r.Run(":8080") }

2.2 Single static file

go
func main() { r := gin.Default() // Provide single static file r.StaticFile("/favicon.ico", "./resources/favicon.ico") r.Run(":8080") }

2.3 Static file serving to root path

go
func main() { r := gin.Default() // Serve static files to root path r.StaticFS("/", http.Dir("./public")) r.Run(":8080") }

3. Best practices for templates and static files

3.1 Directory structure

shell
project/ ├── main.go ├── templates/ │ ├── base.html │ ├── index.html │ └── about.html ├── static/ │ ├── css/ │ │ └── style.css │ ├── js/ │ │ └── app.js │ └── images/ │ └── logo.png └── uploads/ └── files/

3.2 Template organization

go
func setupTemplates(r *gin.Engine) { // Load all templates r.LoadHTMLGlob("templates/**/*.html") // Or load templates from different directories separately r.LoadHTMLGlob("templates/*.html") r.LoadHTMLGlob("templates/layouts/*.html") r.LoadHTMLGlob("templates/components/*.html") }

3.3 Static file caching

go
func setupStaticFiles(r *gin.Engine) { // Use file system cache fs := http.Dir("./static") fileServer := http.FileServer(fs) // Add cache headers r.GET("/static/*filepath", func(c *gin.Context) { c.Header("Cache-Control", "public, max-age=3600") fileServer.ServeHTTP(c.Writer, c.Request) }) }

4. Frontend resource optimization

4.1 Compress static resources

go
import "github.com/gin-contrib/gzip" func main() { r := gin.Default() // Enable gzip compression r.Use(gzip.Gzip(gzip.DefaultCompression)) r.Static("/static", "./static") r.Run(":8080") }

4.2 Version control static resources

go
func getVersionedPath(path string) string { info, err := os.Stat(path) if err != nil { return path } return fmt.Sprintf("%s?v=%d", path, info.ModTime().Unix()) } func renderPage(c *gin.Context) { c.HTML(200, "index.html", gin.H{ "cssPath": getVersionedPath("/static/css/style.css"), "jsPath": getVersionedPath("/static/js/app.js"), }) }

5. Template security

5.1 Prevent XSS attacks

go
// Gin escapes HTML by default to prevent XSS func renderSafe(c *gin.Context) { // Auto escape c.HTML(200, "index.html", gin.H{ "content": "<script>alert('xss')</script>", }) // If you need to output raw HTML, use template.HTML c.HTML(200, "index.html", gin.H{ "content": template.HTML("<div>Safe HTML</div>"), }) }

5.2 CSRF protection

go
import "github.com/utrack/gin-csrf" func main() { r := gin.Default() // Configure CSRF middleware r.Use(csrf.New(csrf.Options{ Secret: "csrf-secret-key", ErrorFunc: func(c *gin.Context) { c.String(400, "CSRF token mismatch") }, })) r.GET("/form", func(c *gin.Context) { c.HTML(200, "form.html", gin.H{ "csrf": csrf.GetToken(c), }) }) r.POST("/submit", func(c *gin.Context) { // Handle form submission }) r.Run(":8080") }

6. Responsive design support

6.1 Mobile detection

go
func isMobile(c *gin.Context) bool { userAgent := c.GetHeader("User-Agent") mobileRegex := regexp.MustCompile(`(Android|iPhone|iPad|iPod)`) return mobileRegex.MatchString(userAgent) } func renderResponsive(c *gin.Context) { templateName := "index.html" if isMobile(c) { templateName = "mobile.html" } c.HTML(200, templateName, gin.H{ "isMobile": isMobile(c), }) }

7. Best practices summary

  1. Template management

    • Use template inheritance to reduce duplicate code
    • Reasonably organize template directory structure
    • Use custom template functions to improve reusability
  2. Static files

    • Enable gzip compression
    • Set reasonable cache policies
    • Use CDN to accelerate static resources
  3. Security

    • Escape HTML by default to prevent XSS
    • Implement CSRF protection
    • Validate and filter user input
  4. Performance optimization

    • Use template caching
    • Compress static resources
    • Implement resource versioning
  5. Development experience

    • Support hot reload
    • Provide clear error messages
    • Use template debugging tools

Through the above methods, you can efficiently implement template rendering and static file serving in the Gin framework.

标签:Gin