liveBook · Manning

Http.FileServer

As explained in Go in Practice, Second Edition

http.FileServer is a Go net/http function that returns an HTTP handler for serving files rooted at a filesystem directory.

http.FileServer returns a handler that serves files from an http.Dir rooted at a local filesystem directory. It can serve static application assets such as CSS, images, and JavaScript. section 10.1

Serve a directory

dir := http.Dir("./files") if err := http.ListenAndServe(":8080", http.FileServer(dir)); err != nil { panic(err) }

Important operational details:

  • Serves files only when filesystem permissions allow access and can return 304 Not Modified when If-Modified-Since matches the current file. section 10.1
  • Fails silently at construction when the directory does not exist; requests instead produce 404 responses, so deployment should verify the directory. section 10.1
  • Use http.StripPrefix when mounting a filesystem directory beneath a URL path such as /static/. section 10.1.1
  • Choose http.ServeFile for a custom handler serving one known file or when built-in error behavior needs replacement. section 10.1

How Go in Practice, Second Edition covers it

How deep it goes
Explains construction, routing, caching responses, missing directories, and alternatives, but does not detail handler internals.
Examples
Uses ./files, /static/, Listing 10.1 directory serving, and Listing 10.3 prefixed subdirectory routing.
What it assumes
Assumes basic Go HTTP handlers and filesystem paths while demonstrating the required standard-library setup.
What you can do after
Operate/configure a Go HTTP server that serves filesystem assets and mounts them beneath a URL prefix.
How it connects
Connects http.Dir, http.StripPrefix, http.ServeFile, filesystem permissions, and If-Modified-Since caching.

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.