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

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

http.FileServer 只服務于 index.html

http.FileServer 只服務于 index.html

Go
達令說 2022-04-26 15:26:56
我的簡單文件服務器代碼:package mainimport (    "net/http"    "os"    "github.com/gorilla/handlers"    "github.com/gorilla/mux")func main() {    r := mux.NewRouter()    // default file handler    r.Handle("/", http.FileServer(http.Dir("web")))    // run on port 8080    if err := http.ListenAndServe(":8080", handlers.LoggingHandler(os.Stdout, r)); err != nil {        panic(err)    }}我的目錄結構是:cmd/server/main.goweb/index.htmlweb/favicon.icoweb/favicon.pngweb/css/main.cssindex.html要求main.css。所以當我運行時,go run cmd/server/main.go我得到以下輸出:127.0.0.1 - - [24/Dec/2019:22:45:26 -0X00] "GET / HTTP/1.1" 304 0127.0.0.1 - - [24/Dec/2019:22:45:26 -0X00] "GET /css/main.css HTTP/1.1" 404 19我可以看到該index.html頁面,但沒有 CSS。當我請求任何其他文件(例如favicon.ico)時,我也會收到 404。為什么我的FileServer唯一服務index.html?
查看完整描述

1 回答

?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

為了說明為什么這不起作用,請考慮以下測試應用程序:


package main


import (

    "fmt"

    "net/http"


    "github.com/gorilla/mux"

)


type testHandler struct{}


func (h *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    fmt.Printf("Got request for %s\n", r.URL)

}


func main() {

    r := mux.NewRouter()

    hndlr := testHandler{}

    r.Handle("/", &hndlr)


    // run on port 8080

    if err := http.ListenAndServe(":8080", r); err != nil {

        panic(err)

    }

}

如果您http://127.0.0.1:8080/在瀏覽器中運行并訪問它,它將記錄Got request for /. 但是,如果您訪問 http://127.0.0.1:8080/foo,您將收到 404 錯誤,并且不會記錄任何內容。這是因為r.Handle("/", &hndlr)只會匹配它,/而不是它下面的任何東西。


如果將其更改為r.PathPrefix("/").Handler(&hndlr),它將按預期工作(路由器會將所有路徑傳遞給處理程序)。因此,要將您的示例更改r.Handle("/", http.FileServer(http.Dir("web")))為r.PathPrefix("/").Handler( http.FileServer(http.Dir("web"))).


注意:因為這是傳遞所有路徑,FileServer所以實際上不需要使用 Gorilla Mux;假設您將使用它來添加其他一些路線,我將其保留。


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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