Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 ยท Templates and Static Files

Static Files and Embedding Assets in Gin

Serve CSS, images and JavaScript from Gin with r.Static, StaticFS, StaticFile and c.File, add cache headers, and ship everything in one binary with go:embed.

A web page is more than HTML: it needs stylesheets, scripts, images and fonts. These static files do not change per request, so the server only has to find them on disk and send them with the right Content-Type. Gin gives you a few short helpers for that, and Go's embed package lets you compile the files into your binary so deployment is a single file.

As in the rest of this chapter, Gin is not available in the in-page runner. The Gin calls are read-only snippets, and the runnable examples are stand-ins built on net/http and testing/fstest, which Gin uses underneath: r.Static is a thin wrapper around http.FileServer.

The static helpers

Go
r := gin.Default()

r.Static("/assets", "./public")          // GET /assets/app.css -> ./public/app.css
r.StaticFile("/favicon.ico", "./public/favicon.ico")
r.StaticFS("/more", http.Dir("./uploads"))  // any http.FileSystem

r.GET("/report", func(c *gin.Context) {
	c.File("./reports/2025.pdf")            // one file, chosen in code
})
  • Static(urlPrefix, dir) maps a URL prefix to a directory. Request /assets/css/site.css and Gin serves ./public/css/site.css.
  • StaticFile(url, path) serves one fixed file at one URL.
  • StaticFS(prefix, fs) is the general form: it accepts any http.FileSystem, for example an embedded one.
  • c.File(path) sends one file from inside a handler, useful when the path depends on the user or on a database lookup.
  • c.FileAttachment(path, "name.pdf") sends it as a download with a Content-Disposition: attachment header.

By default a directory without an index.html is not listed: Gin's Static disables directory listings, which is the safe choice. http.Dir blocks .. path tricks, so /assets/../secret cannot escape the folder.

What the file server does for you

Besides reading the bytes, the standard file server sets Content-Type from the file extension, supports Range requests (video seeking, resumable downloads), handles If-Modified-Since for conditional requests (answering 304), and serves index.html for directory URLs. Try it with an in-memory file system, which behaves like a directory but needs no files on disk:

Go A file server over an in-memory folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The Content-Type came from the extension, and the missing file gives 404. Gin's Static does the same, plus StripPrefix, so you only write the prefix once.

Cache headers

Browsers cache static files, and a good Cache-Control header makes your site much faster. Two common strategies:

  • Fingerprinted file names (app.3f9c1b.css): the name changes whenever the content changes, so you can cache them for a year with immutable.
  • Plain names (app.css): use no-cache or a short max-age and rely on revalidation (ETag, Last-Modified).

Gin has no built-in option for this, so you wrap the static route in a tiny middleware (the Middleware chapter covers them in depth):

Go
func cacheFor(d time.Duration) gin.HandlerFunc {
	value := fmt.Sprintf("public, max-age=%d", int(d.Seconds()))
	return func(c *gin.Context) {
		c.Header("Cache-Control", value)
		c.Next()
	}
}

assets := r.Group("/assets", cacheFor(24*time.Hour))
assets.Static("/", "./public")

Here is the idea running on the standard library, with a handler wrapper doing the same job:

Go Adding Cache-Control to static files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Embedding assets in the binary

With Static, the binary needs the public folder next to it on the server. If you forget to copy it, the site loses its styles. The embed package (see Embedding Files) compiles the files into the program:

Go
//go:embed public
var publicFS embed.FS

//go:embed templates/*.tmpl
var templatesFS embed.FS

func main() {
	r := gin.Default()

	// Templates from the embedded FS
	tpl := template.Must(template.ParseFS(templatesFS, "templates/*.tmpl"))
	r.SetHTMLTemplate(tpl)

	// Static files: strip the "public" folder from the embedded path
	sub, _ := fs.Sub(publicFS, "public")
	r.StaticFS("/assets", http.FS(sub))

	r.Run(":8080")
}

Three things to notice. SetHTMLTemplate replaces LoadHTMLGlob when your templates are not on disk. fs.Sub removes the public/ prefix so /assets/app.css maps to public/app.css. And http.FS adapts an fs.FS to the http.FileSystem that StaticFS expects. The result: one executable that contains code, templates, CSS and images, ideal for a small container image (see Docker and Deployment).

Embedding happens at compile time. Edit a CSS file and you must rebuild. During development, serve from disk with r.Static, and switch to embedding for release builds with a build tag or an environment flag.

Try it: switching between disk and embedded

The same code can serve from either source if you program against fs.FS. This stand-in shows fs.Sub removing a prefix, exactly as in the Gin snippet:

Go fs.Sub strips the embedded folder prefix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The second request fails because after fs.Sub the folder name public is no longer part of the path. This is the bug people hit most often when they embed: a 404 for files that obviously exist.

Common mistakes

  • Mounting Static("/", "./public") while also registering other root routes. Use a prefix such as /assets to avoid route conflicts.
  • Serving a user-supplied path with c.File(c.Query("f")). That lets visitors read any file. Look the file up by an ID instead, or clean and verify the path stays inside one folder.
  • Forgetting //go:embed needs the files to exist at build time and must sit in the same module, below the Go file.
  • Putting secrets (.env, private keys) in a folder that you serve.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does r.Static("/assets", "./public") do?

    Static maps a URL prefix to a directory and serves matching files with the right content type.
  2. 2. Which helper accepts any http.FileSystem, such as an embedded one?

    StaticFS takes an http.FileSystem, so you can pass http.FS(embeddedFS) or http.Dir(...).
  3. 3. Why call fs.Sub(publicFS, "public") before StaticFS?

    Embedded paths include the folder name. Sub returns a file system rooted inside it, so /assets/app.css finds public/app.css.
  4. 4. Which handler is the safest way to send a user-selected file?

    Passing user input straight to c.File can expose any file on the machine. Map an ID to a known path instead.
  5. 5. A fingerprinted file name such as app.3f9c1b.css allows which caching strategy?

    When the name changes with the content, an old URL never changes, so it can be cached for a long time.

Summary

  • Static, StaticFile, StaticFS and c.File serve files; Static is a wrapper around the standard file server and hides directory listings.
  • Add Cache-Control with a small middleware or group.
  • embed plus fs.Sub, http.FS and StaticFS ship assets inside the binary.
  • Never pass user input directly as a file path.

Next: File Uploads and Downloads