DEV Community

loading...

Golang: HTTP Serve static files correctly

hauxe profile image Hậu Xe ・1 min read

Demo

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:
https://gist.github.com/hauxe/09cd680deb9c8c4e36d61568db57647b

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:
https://gist.github.com/hauxe/f88a87f4037bca23f04f6d100f6e08d4#file-http_static_custom_http_server-go

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:
https://gist.github.com/hauxe/f2ea1901216177ccf9550a1b8bd59178#file-http_static_correct-go


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

Discussion (0)

pic
Editor guide