StripPrefix Serves Files Under A Subpath
StripPrefix removes a fixed path prefix before a FileServer, so static assets live under one URL subtree without moving files on disk.
Code
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing/fstest"
)
func main() {
// fstest.MapFS 提供内存文件系统:不需要真实磁盘文件
files := fstest.MapFS{
"style.css": {Data: []byte("body{}")},
}
// StripPrefix 先剥掉 /static/ 前缀,FileServer 在剩余路径里找文件
handler := http.StripPrefix("/static/", http.FileServer(http.FS(files)))
server := httptest.NewServer(handler)
defer server.Close()
resp, err := http.Get(server.URL + "/static/style.css")
if err != nil {
fmt.Println("get:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println("status:", resp.StatusCode)
fmt.Printf("body: %s\n", body)
// 前缀剥掉后不存在的文件:FileServer 返回 404
miss, _ := http.Get(server.URL + "/static/missing.css")
defer miss.Body.Close()
fmt.Println("missing status:", miss.StatusCode)
}The shape of the program
Every bit of the logic sits in the function main.
err is inspected at 1 call site before any result is trusted. Cleanup is attached with defer, so it runs on every exit path of the function.
Caveats
- Nothing to install: the snippet draws only on the standard library.
Applying it
The main signature, as written: func main()
Each step in the output carries its own tag: get:, status:, body:.
Statements that matter
if err != nil {
fmt.Println("get:", err)
return
}
defer resp.Body.Close()
defer miss.Body.Close()
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
FAQ
- What does StripPrefix Serves Files Under A Subpath print when run?
- Run it as a complete program — the output lines carry labels such as `get:`, `status:`, `body:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.