DEV Community

Hậu Xe
Hậu Xe

Posted on

Golang: HTTP Serve static files correctly


The EasyWay

Handle static files in Golang is very straightforward just one line of code to do this:

http.Handle("/", http.StripPrefix(strings.TrimRight(path, "/"), http.FileServer(http.Dir(directory))))

where path is http path and directory is the static directory you want to serve over http

But, there is a problem, by accessing to root url you can expose your directory structure to public as well =_=:

listing directory

The code is:

We need to do something to prevent this danger

First Don’t use default HTTP File server, we’ll create our custome http file server and reject which request accessing to directory path:

The custom rule that I chose is: if accessing to a directory, and if that directory contains index.html, return it, otherwise return error

Second Register HTTP File server with this custom struct:

fileServer := http.FileServer(FileSystem{http.Dir(directory)})

http.Handle("/", http.StripPrefix(strings.TrimRight(path, "/"), fileServer))

If you access it again:

Successfully prevents

Put a index.html file into statics folder and run example again with new code:

After put index.html

Full working code:

I have made a Repo for this purpose which return the http handler for it

Top comments (0)