DEV Community

Hậu Xe
Hậu Xe

Posted on

12 2

Golang: HTTP Serve static files correctly

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))))
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay