HTTP File Server
Start with HTTP File Server
Learn http file server through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of http file server.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Go’s http.FileServer exposes files through an HTTP handler. Use an explicitly chosen root and protect private files; do not expose your home directory or repository tree unintentionally.
The example serves a virtual filesystem in memory with fstest.MapFS, avoiding local file access.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Deployment: configure a dedicated public directory or embed.FS, apply authentication where required, set caching headers deliberately and test path traversal attempts.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing/fstest"
)
func main() {
files := fstest.MapFS{"readme.txt": &fstest.MapFile{Data: []byte("Go file server")}}
handler := http.FileServer(http.FS(files))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest("GET", "/readme.txt", nil))
body, err := io.ReadAll(recorder.Result().Body)
if err != nil {
panic(err)
}
fmt.Println("Status:", recorder.Code, "Body:", string(body))
}
Output
Status: 200 Body: Go file serverTrace what the program does
The FileServer reads readme.txt from the in-memory filesystem and returns it with HTTP 200. The response is inspected without opening an external network port.
Avoid common mistakes
- Avoid serving private files or following unexpected symlinks from a broad root.
- Authentication and file listing rules must be explicit for nonpublic content.
Try it yourself
Serve an assets directory using http.Dir, disable unwanted directory listing and test missing files.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced HTTP File Server in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.