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.

GoData Fetching

Code

snippet
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

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:`.