Whenever I want to set up a server for serving static files in Go, which is not often, I always have to spend some time to figure out the following one-liner.
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("./images"))))
What confuses me probably the most here is all three strings being practically the same.
So in this post I will explain what this does for my future-self so he won’t have to google about it and will have it explained here in a way he’ll like it. 🙂
For this particular example (where one-liner above applies) let’s say we are storing images in ./images
folder on a server and accessing them from outside of the server with <server's domain>/images/article2.jpeg
- We shouldn’t set up a file server at root endpoint if our server accepts other endpoints.
http.FileServer(http.Dir("./images")))
exposes folder./images
as a handler.http.StripPrefix
is used because images are stored in./images`
folder and not in it’s subfolderimages
(we want./images/article2.jpeg
not./images/images/article2.jpeg
). It strips prefix from request’s URL.
A friendly reminder
Serving static files is more efficient using dedicated web server (Nginx, Apache,..). This approach also aids to better security of your application.