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
