Skip to content

Go http.ServeFile vs http.FileServer — Complete Guide

DodaTech Updated 2026-06-24 1 min read

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
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

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. 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

**Does http.FileServer prevent directory listing?**

No. By default it shows directory contents if no index.html exists. Use a custom http.FileSystem implementation to block it.

Can I serve files from an embedded FS?

Yes, use http.FS(embed.FS) with Go's embed package for embedded static content in Go 1.16+.

How do I restrict FileServer to specific extensions?

Wrap http.Dir with a custom FileSystem that checks file extensions in Open() before delegating to the real filesystem.


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