Gin foundations · 5 MIN READ
Server-rendered HTML in Gin: embed the templates, trust contextual escaping, cache assets on purpose
Render html/template pages with c.HTML from templates parsed out of an embedded file system, serve embedded static assets with StaticFS and set cache headers per kind of asset.
Gin can render server-side HTML with very little code, and Go's html/template does the hardest part, escaping, for you. What Gin leaves to you are the operational decisions: how templates reach the binary, what happens when a template fails halfway, whether a directory listing is exposed and how long browsers and CDNs may keep each file.
gin · A MAP OF THE IDEA
- Embed templates and assets
- Parse once at startup
- Buffer all-or-nothing pages
- Cache by asset class
Useful when
- Contextual escaping covers HTML, attributes, URLs and scripts.
- Embedded templates and assets ship inside one binary.
Watch out
- Template errors after c.HTML starts still return 200.
- Plain http.FS exposes directory listings through StaticFS.
Implementation & operation cost: One startup parse, a buffer per buffered page and a cache policy to maintain alongside the build step that fingerprints assets.
html/template escapes by context; Gin only picks the template
c.HTML(code, name, data) asks the engine's HTMLRender for the named template and executes it into the response with Content-Type text/html; charset=utf-8. The escaping comes from html/template, which parses the template's HTML structure and escapes each action for the context it appears in: element text, an attribute, a URL, a script or a style. The same string therefore gets different encodings in different places, and none of them can break out of its context. Two rules keep that guarantee: import html/template, never text/template, for HTML, and reserve template.HTML, template.URL and template.JS for content you produced yourself, because those types switch escaping off.
A page, its assets and two failure modes
The program parses two templates from a file system, renders a profile whose display name is an XSS payload, serves two static files through StaticFS with different cache rules and shows what happens when a template is missing, with and without buffered rendering. An fstest.MapFS stands in for embed.FS because go:embed needs files next to the source; both implement fs.FS, so the code is the same.
package main
import (
"bytes"
"fmt"
"html/template"
"io/fs"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing/fstest"
"github.com/gin-gonic/gin"
)
// site stands in for an embed.FS; the files are inline so the lesson is one main.go.
var site = fstest.MapFS{
"templates/header.html": {Data: []byte(`{{define "header"}}<!doctype html><title>{{.Title}}</title>` +
`<link rel="stylesheet" href="{{asset "app.css"}}">{{end}}`)},
"templates/profile.html": {Data: []byte(`{{define "profile.html"}}{{template "header" .}}` +
`<h1>{{.Name}}</h1><a href="/search?q={{.Name}}">search</a><script>const name = {{.Name}};</script>{{end}}`)},
"static/app.5d41402a.css": {Data: []byte("body{margin:0}")},
"static/logo.svg": {Data: []byte(`<svg xmlns="http://www.w3.org/2000/svg"/>`)},
}
// manifest maps logical asset names to the fingerprinted files a build step wrote.
var manifest = map[string]string{"app.css": "app.5d41402a.css"}
var fingerprinted = regexp.MustCompile(`\.[0-9a-f]{8}\.`)
func cacheAssets(fsys fs.FS) gin.HandlerFunc {
return func(c *gin.Context) {
name := strings.TrimPrefix(c.Param("filepath"), "/")
info, err := fs.Stat(fsys, name)
switch {
case err != nil || info.IsDir():
// No cache header on 404s.
case fingerprinted.MatchString(name):
c.Header("Cache-Control", "public, max-age=31536000, immutable")
default:
c.Header("Cache-Control", "public, max-age=300")
}
}
}
// renderPage executes into a buffer so a template error becomes a clean 500.
func renderPage(c *gin.Context, t *template.Template, name string, data any) {
var buf bytes.Buffer
if err := t.ExecuteTemplate(&buf, name, data); err != nil {
_ = c.Error(err)
c.String(http.StatusInternalServerError, "page unavailable")
return
}
c.Data(http.StatusOK, "text/html; charset=utf-8", buf.Bytes())
}
func main() {
gin.SetMode(gin.TestMode)
funcs := template.FuncMap{"asset": func(name string) string { return "/static/" + manifest[name] }}
tmpl := template.Must(template.New("").Funcs(funcs).ParseFS(site, "templates/*.html"))
r := gin.New()
r.SetHTMLTemplate(tmpl)
r.GET("/users/:id", func(c *gin.Context) {
c.Header("Cache-Control", "no-cache")
c.HTML(http.StatusOK, "profile.html", gin.H{"Title": "Profile", "Name": `<img src=x onerror=alert(1)>`})
})
r.GET("/broken", func(c *gin.Context) { c.HTML(http.StatusOK, "missing.html", nil) })
r.GET("/broken-buffered", func(c *gin.Context) { renderPage(c, tmpl, "missing.html", nil) })
static, err := fs.Sub(site, "static")
if err != nil {
panic(err)
}
assets := r.Group("/static", cacheAssets(static))
assets.StaticFS("/", &gin.OnlyFilesFS{FileSystem: http.FS(static)})
for _, path := range []string{
"/users/7", "/broken", "/broken-buffered",
"/static/app.5d41402a.css", "/static/logo.svg", "/static/missing.css",
} {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
fmt.Printf("%s %d type=%q cache=%q bytes=%d\n", path, w.Code,
w.Header().Get("Content-Type"), w.Header().Get("Cache-Control"), w.Body.Len())
if strings.HasPrefix(path, "/users/") {
fmt.Println(w.Body.String())
}
}
}Funcs is called before ParseFS because a template that mentions asset cannot parse without it. The payload is escaped three ways: as <img in the heading, percent-encoded in the href query and as a quoted JavaScript string with \u003c inside the script. /broken shows the trap: c.HTML has already chosen 200 when the lookup fails, so the client gets an empty 200 page. renderPage executes into a buffer first and turns the same error into a 500. The fingerprinted stylesheet gets a year-long immutable lifetime, the logo five minutes, and the missing file no cache header at all.
Load templates from an embedded file system
Gin v1.12.0 offers LoadHTMLGlob, LoadHTMLFiles and LoadHTMLFS(fs http.FileSystem, patterns...). With an embed.FS you would call r.LoadHTMLFS(http.FS(site), "templates/*.html"), which panics through template.Must if a template does not parse. In debug mode all three install a renderer that re-parses on every request, useful for files on disk during development and pointless for embedded ones. Parsing yourself with template.ParseFS and handing the result to SetHTMLTemplate returns an ordinary error and leaves you holding the *template.Template for buffered rendering. All files share one namespace, so if two pages each {{define "content"}}, the last one parsed silently wins. Give blocks unique names, as the program does, or build one template set per page behind a custom render.HTMLRender.
//go:embed templates/*.html static
var site embed.FS
func newRouter() (*gin.Engine, error) {
tmpl, err := template.New("").Funcs(funcs).ParseFS(site, "templates/*.html")
if err != nil {
return nil, err // a syntax error fails startup, not a request
}
static, err := fs.Sub(site, "static")
if err != nil {
return nil, err
}
r := gin.New()
r.SetHTMLTemplate(tmpl) // before serving: it is not safe to swap later
assets := r.Group("/static", cacheAssets(static))
assets.StaticFS("/", &gin.OnlyFilesFS{FileSystem: http.FS(static)})
return r, nil
}This fragment is the production shape; build it in your own module with templates/ and static/ directories next to the source file, which the go:embed line compiles into the binary. It is the program's code with embed.FS in place of fstest.MapFS. Gin calls tmpl.Funcs(engine.FuncMap) inside SetHTMLTemplate, but functions used by templates must already be registered before parsing, which is why funcs is passed to template.New("").Funcs.
A template error after the status is a silent 200
c.HTML records the status and then executes the template straight into the response writer. If execution fails, Gin appends the error to c.Errors and aborts, but the status is already 200 and any HTML written so far has gone to the client. A missing template yields an empty 200 page; a failure halfway through, for example a method returning an error on a nil field, yields half a page. For pages that must be all-or-nothing, execute into a bytes.Buffer and send it with c.Data, as renderPage does. The cost is holding the page in memory, which is negligible for typical pages and wrong for very large streamed reports.
Serve embedded assets with explicit cache rules
StaticFS("/static", fs) registers GET and HEAD for /static/*filepath. With a plain http.FS, a request for a directory returns an HTML listing of its files. Wrapping the file system in &gin.OnlyFilesFS, which must be a pointer because that is the type Gin checks, turns directory requests into 404s; missing files run the NoRoute handlers or return an empty 404. Files in an embed.FS have a zero modification time, so http.FileServer sends no Last-Modified header, and it never computes an ETag, so browsers cannot revalidate cheaply. Set Cache-Control yourself: a year with immutable for fingerprinted names that change whenever the content does, a short max-age for stable names, and no-cache for HTML. Set the header only after confirming the file exists, as cacheAssets does, so a CDN never stores a 404 for a year.
Test pages and assets like any other response
Execute every page once in a test with representative data, including hostile strings and nil fields. html/template computes its escaping on first execution, so some template errors appear only then, not at parse time. Assert the Content-Type, the escaped forms of the payload in each context, the Cache-Control value per kind of asset, a 404 for a directory and a 500 rather than an empty 200 for a failing page.
TAKE THIS WITH YOU
Parse html/template files from an embedded FS at startup, render pages that must not fail halfway through a buffer, disable directory listings with OnlyFilesFS and give each class of asset an explicit Cache-Control.
Check your understanding
Why does renderPage execute the template into a bytes.Buffer instead of calling c.HTML directly?
Go to the source
Progress stays in this browser. No account needed.