1 回答

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超6個(gè)贊
為了說(shuō)明為什么這不起作用,請(qǐng)考慮以下測(cè)試應(yīng)用程序:
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/在瀏覽器中運(yùn)行并訪問(wèn)它,它將記錄Got request for /. 但是,如果您訪問(wèn) http://127.0.0.1:8080/foo,您將收到 404 錯(cuò)誤,并且不會(huì)記錄任何內(nèi)容。這是因?yàn)閞.Handle("/", &hndlr)只會(huì)匹配它,/而不是它下面的任何東西。
如果將其更改為r.PathPrefix("/").Handler(&hndlr),它將按預(yù)期工作(路由器會(huì)將所有路徑傳遞給處理程序)。因此,要將您的示例更改r.Handle("/", http.FileServer(http.Dir("web")))為r.PathPrefix("/").Handler( http.FileServer(http.Dir("web"))).
注意:因?yàn)檫@是傳遞所有路徑,F(xiàn)ileServer所以實(shí)際上不需要使用 Gorilla Mux;假設(shè)您將使用它來(lái)添加其他一些路線,我將其保留。
- 1 回答
- 0 關(guān)注
- 176 瀏覽
添加回答
舉報(bào)