首先我們看下標准庫文檔中定義以及解釋
func StripPrefix(prefix string, h Handler) Handler
StripPrefix返回一個處理器,該處理器會將請求的URL.Path字段中給定前綴prefix去除后再交由h處理。StripPrefix會向URL.Path字段中沒有給定前綴的請求回復404 page not found。
// 官方提供的demo
// To serve a directory on disk (/tmp) under an alternate URL
// 在備用URL下在磁盤(/tmp)上提供目錄
// path (/tmpfiles/), use StripPrefix to modify the request
// 路徑(/tmpfiles/),使用StripPrefix修改請求
// URL's path before the FileServer sees it:
// 文件服務器看到它之前的URL路徑:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
翻譯過來的參數簽名是這樣的
http.Handle("url/Prefix", http.StripPrefix("/Prefix", http.FileServer(http.Dir("/now"))))
// 等於是訪問到的url/now路徑
同時 Go很輕易就可以搭建一個文件服務器
http.Handle("/", http.StripPrefix("/file", http.FileServer(http.Dir("./static"))))
// 訪問 127.0.0.1:8888/file/hello -> hello world
// 文件目錄
// - main.go
// - static
// -/- hello
http.ListenAndServe(":8888", nil)