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