Go http.ServeFile vs http.FileServer — Complete Guide
In this tutorial, you'll learn about Go http.ServeFile vs http.FileServer. We cover key concepts, practical examples, and best practices.
File serving in Go -- Learn the difference between ServeFile for single files and FileServer for directories to serve static content correctly.
The Problem
http.ServeFile strips the filename from the request when serving a single file, but http.FileServer uses the request path to locate files. Confusing these leads to 404 errors, directory listing leaks, or path traversal vulnerabilities.
Wrong
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/index.html")
})
Output:
$ curl http://localhost:8080/about
// Always returns index.html content
Right
http.Handle("/static/", http.StripPrefix("/static/",
http.FileServer(http.Dir("./static"))))
Output:
$ curl http://localhost:8080/static/style.css
// Returns ./static/style.css correctly
Prevention
- Use http.FileServer for directory-based static file serving
- Use http.ServeFile only for serving a single known file
- Always use http.StripPrefix when mounting FileServer under a path prefix
- Never pass user input directly to ServeFile without sanitization
- Set Content-Type headers explicitly if Go's detection is unreliable
Common Mistakes with http serve file
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro