在go文件服務(wù)器加入http.StripPrefix的用途介紹
例子:
http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
當(dāng)訪問localhost:xxxx/tmpfiles時,會路由到fileserver進(jìn)行處理
當(dāng)訪問URL為/tmpfiles/example.txt時,fileserver會將/tmp與URL進(jìn)行拼接,得到/tmp/tmpfiles/example.txt,而實際上example.txt的地址是/tmp/example.txt,因此這樣將訪問不到相應(yīng)的文件,返回404 NOT FOUND。
因此解決方案就是把URL中的/tmpfiles/去掉,而http.StripPrefix做的就是這個。
補(bǔ)充: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))
}
}
準(zhǔn)備測試文件

編譯運(yùn)行

用瀏覽器訪問


以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
源碼剖析Golang中map擴(kuò)容底層的實現(xiàn)
之前的文章詳細(xì)介紹過Go切片和map的基本使用,以及切片的擴(kuò)容機(jī)制。本文針對map的擴(kuò)容,會從源碼的角度全面的剖析一下map擴(kuò)容的底層實現(xiàn),需要的可以參考一下2023-03-03
Go語言實現(xiàn)管理多個數(shù)據(jù)庫連接
在軟件開發(fā)過程中,使用?MySQL、PostgreSQL?或其他數(shù)據(jù)庫是很常見的,由于配置和要求不同,管理這些連接可能具有挑戰(zhàn)性,下面就來和大家聊聊如何在Go中管理多個數(shù)據(jù)庫連接吧2023-10-10
CMD下執(zhí)行Go出現(xiàn)中文亂碼的解決方法
需要在Go寫的服務(wù)里面調(diào)用命令行或者批處理,并根據(jù)返回的結(jié)果做處理。但是windows下面用cmd返回中文會出現(xiàn)亂碼,本文就詳細(xì)的介紹一下解決方法,感興趣的可以了解一下2021-12-12
go?zero微服務(wù)實戰(zhàn)性能優(yōu)化極致秒殺
這篇文章主要為大家介紹了go-zero微服務(wù)實戰(zhàn)性能優(yōu)化極致秒殺功能實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Golang在Window環(huán)境使用Imagick7的過程
這篇文章主要介紹了Golang在Window環(huán)境使用Imagick7的過程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-11-11

