例子:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
當訪問localhost:xxxx/tmpfiles時,會路由到fileserver進行處理
當訪問URL為/tmpfiles/example.txt時,fileserver會將/tmp與URL進行拼接,得到/tmp/tmpfiles/example.txt,而實際上example.txt的地址是/tmp/example.txt,因此這樣將訪問不到相應的文件,返回404 NOT FOUND。
因此解決方案就是把URL中的/tmpfiles/去掉,而http.StripPrefix做的就是這個。
補充:go語言實現一個簡單的文件服務器 http.FileServer
代碼如下:
package main import ( "flag" "fmt" "github.com/julienschmidt/httprouter" "log" "net/http" "strings" "time" ) func main() { root := flag.String("p", "", "file server root directory") flag.Parse() if len(*root) == 0 { log.Fatalln("file server root directory not set") } if !strings.HasPrefix(*root, "/") { log.Fatalln("file server root directory not begin with '/'") } if !strings.HasSuffix(*root, "/") { log.Fatalln("file server root directory not end with '/'") } p, h := NewFileHandle(*root) r := httprouter.New() r.GET(p, LogHandle(h)) log.Fatalln(http.ListenAndServe(":8080", r)) } func NewFileHandle(path string) (string, httprouter.Handle) { return fmt.Sprintf("%s*files", path), func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { http.StripPrefix(path, http.FileServer(http.Dir(path))).ServeHTTP(w, r) } } func LogHandle(handle httprouter.Handle) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { now := time.Now() handle(w, r, p) log.Printf("%s %s %s done in %v", r.RemoteAddr, r.Method, r.URL.Path, time.Since(now)) } }
準備測試文件
編譯運行
用瀏覽器訪問
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。