亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

第二個 FileServer 提供 html 但不提供圖像

第二個 FileServer 提供 html 但不提供圖像

Go
紅顏莎娜 2022-05-23 15:58:08
gorilla/mux在構建簡單的 API 時,我遇到了 Go 和路由器的以下問題。我確信這是我臉上常見的愚蠢錯誤,但我看不到它。簡化的項目結構|--main.go||--public/--index.html|        |--image.png||--img/--img1.jpg|     |--img2.jpg|     |--...|...main.gopackage mainimport (    "net/http"    "github.com/gorilla/mux")var Router = mux.NewRouter()func InitRouter() {    customers := Router.PathPrefix("/customers").Subrouter()    customers.HandleFunc("/all", getAllCustomers).Methods("GET")    customers.HandleFunc("/{customerId}", getCustomer).Methods("GET")    // ...    // Registering whatever middleware    customers.Use(middlewareFunc)    users := Router.PathPrefix("/users").Subrouter()    users.HandleFunc("/register", registerUser).Methods("POST")    users.HandleFunc("/login", loginUser).Methods("POST")    // ...    // Static files (customer pictures)    var dir string    flag.StringVar(&dir, "images", "./img/", "Directory to serve the images")    Router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))    var publicDir string    flag.StringVar(&publicDir, "public", "./public/", "Directory to serve the homepage")    Router.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(publicDir))))}func main() {    InitRouter()    // Other omitted configuration    server := &http.Server{        Handler: Router,        Addr:    ":" + port,        // Adding timeouts        WriteTimeout: 15 * time.Second,        ReadTimeout:  15 * time.Second,    }    err := server.ListenAndServe()    // ...}子路由工作正常,中間件和所有。img如果我去下面的圖像是正確的localhost:5000/static/img1.png。問題是,將localhost:5000服務于index.html駐留的public,但隨后localhost:5000/image.png是 a 404 not found。這里發生了什么?
查看完整描述

1 回答

?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

更改此行:


// handles '/' and *ONLY* '/'

Router.Handle("/",

        http.StripPrefix("/", http.FileServer(http.Dir(publicDir))))

對此:


// handles '/' and all sub-routes

Router.PathPrefix("/").Handler(

        http.StripPrefix("/",http.FileServer(http.Dir(publicPath))))

基本上,在您的原始代碼中,路由器/正在處理此路徑并且僅處理該路徑(無子路由)。


您可能想知道為什么您的原始代碼至少對一個文件“有效”(index.html)。原因是http.FileServer給定的路徑是目錄 - 而不是文件 - 將默認為索引頁面文件提供服務index.html(請參閱FileServer 源代碼)。


UsingPathPrefix允許 (fileserver) 處理程序接受path 下的所有URL 路徑/。


查看完整回答
反對 回復 2022-05-23
  • 1 回答
  • 0 關注
  • 104 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號