An alternative file server for Go

28 Dec 2015 16:19 GMT

Go's net/http package contains a simple FileServer that lets you map a request path to a directory and serves files under that path like a normal webserver. It's a handy way to serve static files from inside an otherwise dynamic web application.

Go's built-in FileServer is fine if you're just using it for development, but it has two shortcomings if you want to use it in production. First, when it can't find a requested file it responds with a very basic plain text 404 page. Second, when the user requests a path to a directory which does not contain an index page, it shows the directory listing, with no easy way to turn that off.

The FileHandler in the handlers package is an alternative file server that addresses both of these problems. FileHandler lets you specify your own handler for serving 404 pages, and it responds to any request for a directory that does not contain an index page with that handler, rather than show a directory listing. FileHandler is just a wrapper around Go's ServeFile function, so it still has all the goodness of Go's built-in file handling.

The handlers package also contains a simple NotFoundHandler which you can use with FileHandler. But you don't have to. FileHandler can use any type that satisfies the Handler interface to serve custom 404 pages when no matching file is found.