在go文件服務(wù)器加入http.StripPrefix的用途介紹
例子:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
當(dāng)訪問localhost:xxxx/tmpfiles時,會路由到fileserver進行處理
當(dāng)訪問URL為/tmpfiles/example.txt時,fileserver會將/tmp與URL進行拼接,得到/tmp/tmpfiles/example.txt,而實際上example.txt的地址是/tmp/example.txt,因此這樣將訪問不到相應(yīng)的文件,返回404 NOT FOUND。
因此解決方案就是把URL中的/tmpfiles/去掉,而http.StripPrefix做的就是這個。
補充:go語言實現(xiàn)一個簡單的文件服務(wù)器 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)) } }
準備測試文件
編譯運行
用瀏覽器訪問
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Go語言基礎(chǔ)函數(shù)包的使用學(xué)習(xí)
本文通過一個實現(xiàn)加減乘除運算的小程序來介紹go函數(shù)的使用,以及使用函數(shù)的注意事項,并引出了對包的了解和使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05Go并發(fā):使用sync.WaitGroup實現(xiàn)協(xié)程同步方式
這篇文章主要介紹了Go并發(fā):使用sync.WaitGroup實現(xiàn)協(xié)程同步方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05golang類型轉(zhuǎn)換之interface轉(zhuǎn)字符串string簡單示例
在我們使用Golang進行開發(fā)過程中,總是繞不開對字符或字符串的處理,這篇文章主要給大家介紹了關(guān)于golang類型轉(zhuǎn)換之interface轉(zhuǎn)字符串string的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-01-01Golang 語言控制并發(fā) Goroutine的方法
本文我們介紹了不同場景中分別適合哪種控制并發(fā) goroutine 的方式,其中,channel 適合控制少量 并發(fā) goroutine,WaitGroup 適合控制一組并發(fā) goroutine,而 context 適合控制多級并發(fā) goroutine,感興趣的朋友跟隨小編一起看看吧2021-06-06