A file server serves files from a filesystem in response to HTTP requests. Go’s standard library can serve application pages and static assets without a separate web server, although reverse proxies add features such as caching and load balancing. section 10.1
Use the standard-library handlers for common serving tasks:
- Create an http.Dir and pass it to http.FileServer to expose a directory. section 10.1
- Use http.ServeFile inside a custom handler when a route should return one specific file. section 10.1
- Mount a subdirectory under a URL prefix with http.StripPrefix. section 10.1
- Check that the configured directory exists and is accessible; a missing directory produces 404 responses rather than an immediate error. section 10.1
Serving files with a custom error page
The standard file server generates browser-controlled error pages that cannot be customized. A custom file server, such as github.com/Masterminds/go-fileserver, can replace the 404 handler while retaining the standard http.Dir-based directory setup. It can also provide handlers for other error responses. section 10.1.2
Listing 10.1 Serving files via the http package
package main
import (
"net/http"
)
func main() {
dir := http.Dir("./files") #1
if err := http.ListenAndServe(":8080",
http.FileServer(dir)); err != nil { #2
panic(err)
}
}
Runnable Go setup for serving the ./files directory on port 8080 with http.FileServer. section 10.1
Listing 10.4 Custom file server error pages
package main
import (
"fmt"
fs "github.com/Masterminds/go-fileserver" #1
"net/http"
)
func main() {
fs.NotFoundHandler = func(w http.ResponseWriter,
req *http.Request) #2
w.Header().Set("Content-Type", "text/plain;
charset=utf-8")
fmt.Fprintln(w, "The requested page could
not be found.") #3
} #3
dir := http.Dir("./files") #4
http.ListenAndServe(":8080", fs.FileServer(dir)) #5
}
Runnable setup for replacing the default not-found response with a custom handler. section 10.1.2
