liveBook · Manning

Static file

As explained in Go in Practice, Second Edition

A static file is a preexisting file served to clients without being generated dynamically for each request.

A static file is a preexisting asset served to clients rather than generated for each request. In a Go web server, common static files include CSS, JavaScript, images, and other application assets. section 10.0 section 10.1

Choose a serving arrangement according to deployment needs:

  • Serve a directory with http.FileServer and http.Dir; the handler follows filesystem permissions and can return 304 Not Modified for matching If-Modified-Since requests. section 10.1
  • Serve one known file with http.ServeFile from a custom handler, or mount a directory under a URL prefix with http.StripPrefix. section 10.1
  • Embed assets with Go's embed package when the executable should be self-contained; expose an embedded filesystem through http.FS. section 10.1.3
  • Serve assets from a CDN or another location by passing the environment-specific URL into templates as runtime configuration. section 10.1.4

Serving an embedded asset directory

A Go 1.16-or-later application can embed a files directory and serve it without distributing a separate asset directory: `//go:embed files`, `var f embed.FS`, then `http.FileServer(http.FS(f))`. Check filesystem paths when using external directories, because a missing directory can produce 404 responses without an initialization error. section 10.1

Listing 10.5 Embedding files in binaries with go:embed
package main

import (
    "embed"     #1
    "net/http"
)

//go:embed files    #2
var f embed.FS        #3

func main() {
    if err := http.ListenAndServe(":8088", 
    http.FileServer(http.FS(f))); err != nil {   #4
        panic(err)
    }
}

Inspect the complete embedded-filesystem example, including the compiler directive and http.FS adapter. section 10.1.3

How Go in Practice, Second Edition covers it

How deep it goes
Explains directory, single-file, embedded, and external serving, while deferring detailed production deployment mechanics.
Examples
Uses CSS, JavaScript, images, readme.txt, embedded HTML, and environment-specific stylesheet URLs as concrete serving examples.
What it assumes
Assumes basic Go web-server usage and introduces filesystem serving, embedding, templates, and deployment configuration.
What you can do after
Build it from scratch using Go's http.FileServer, ServeFile, embed, http.FS, and configurable asset URLs.
How it connects
Connects static files with HTTP servers, reverse proxies, templates, embedded filesystems, and content delivery networks.

Also explained in

Compare how 6 books explain static file →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.