To start simple, we can return a single file with http.ServeFile()
func FishJson(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/fish.json")
}
This is just like any other Go HTTP handler. You can register this particular one like this:
mux.HandleFunc("GET /2025/fish", FishJson)
It is worth noting that this works with all kinds of files. This can be useful as a way to host a temporary HTML "Coming soon" page.
Sending a single file is great but what if we want to make a directory accessible? We can use built-in Go functions to accomplish this:
func StaticFiles(w http.ResponseWriter, r *http.Request) {
// Create a file server to expose the specified directory
fs := http.FileServer(http.Dir("staticfiles"))
// And remove the path/prefix so the files are accessible directly on /static
http.StripPrefix("/static", fs).ServeHTTP(w, r)
}
This is what it would look like to register the handler:
mux.HandleFunc("GET /static/", StaticFiles)
The folder staticfiles
is local.
Users can access it's contents by going to the /static
endpoint.
One feature of this approach is that your files are viewable because of how http.FileServer()
works.
An example of this is the /static path on this website.