How to Serve Static Files in Go: Simple Guide with Example
In Go, you can serve static files by using
http.FileServer combined with http.StripPrefix to specify the directory. This setup allows your web server to deliver files like images, CSS, or JavaScript directly from a folder.Syntax
Use http.FileServer to create a handler that serves files from a directory. Wrap it with http.StripPrefix if you want to serve files under a specific URL path.
http.FileServer(http.Dir("directory_path")): Serves files from the given directory.http.StripPrefix("/urlpath", handler): Removes the prefix from the URL path before passing it to the handler.http.Handle("/urlpath/", handler): Registers the handler for the URL path.
go
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
Example
This example creates a simple web server that serves files from the static folder when accessed via /static/ URL path.
go
package main import ( "log" "net/http" ) func main() { http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static")))) log.Println("Serving on http://localhost:8080/static/") if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal(err) } }
Output
Serving on http://localhost:8080/static/
Common Pitfalls
- Forgetting the trailing slash in the URL path (e.g., using
/staticinstead of/static/) causes the handler not to match correctly. - Not using
http.StripPrefixleads to incorrect file paths and 404 errors. - Serving files from a directory that does not exist or has no files will cause errors or empty responses.
Example of a common mistake and fix:
go
http.Handle("/static", http.FileServer(http.Dir("./static"))) // Wrong: missing trailing slash and no StripPrefix // Correct: http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
Quick Reference
- http.FileServer: Serves files from a directory.
- http.StripPrefix: Removes URL prefix before serving files.
- Trailing slash in URL path is required for correct matching.
- Place static files in the specified directory (e.g.,
./static).
Key Takeaways
Use http.FileServer with http.Dir to serve files from a folder.
Wrap with http.StripPrefix to remove URL path prefix before serving.
Always include a trailing slash in the URL path when registering the handler.
Ensure the static directory exists and contains the files you want to serve.
Test your server by accessing files via the correct URL path.