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

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

Go 和 Gorilla Mux NotFoundHandler 不工作

Go 和 Gorilla Mux NotFoundHandler 不工作

Go
慕沐林林 2021-08-23 17:48:21
我只是無法讓這個 NotFoundHandler 工作。我想在每個 get 請求上提供一個靜態文件,因為它存在,否則提供 index.html。這是我目前的簡化路由器:func fooHandler() http.Handler {  fn := func(w http.ResponseWriter, r *http.Request) {    w.Write([]byte("Foo"))  }  return http.HandlerFunc(fn)}func notFound(w http.ResponseWriter, r *http.Request) {  http.ServeFile(w, r, "public/index.html")}func main() {  router = mux.NewRouter()  fs := http.FileServer(http.Dir("public"))  router.Handle("/foo", fooHandler())  router.PathPrefix("/").Handler(fs)  router.NotFoundHandler = http.HandlerFunc(notFound)  http.ListenAndServe(":3000", router)}/foo工作正常/file-that-exists工作正常/file-that-doesnt-exist 不起作用 - 我找不到 404 頁面而不是 index.html那么我在這里做錯了什么?
查看完整描述

2 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

問題是router.PathPrefix("/").Handler(fs)將匹配每條路線并且NotFoundHandler永遠不會執行。在NotFoundHandler當路由器不能找到一個匹配的路由時,才會執行。


當您明確定義路由時,它會按預期工作。


你可以這樣做:


router.Handle("/foo", fooHandler())

router.PathPrefix("/assets").Handler(fs)

router.HandleFunc("/", index)

router.HandleFunc("/about", about)

router.HandleFunc("/contact", contact)

router.NotFoundHandler = http.HandlerFunc(notFound)


查看完整回答
反對 回復 2021-08-23
?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

這對我有用

r.NotFoundHandler = http.HandlerFunc(NotFound)

確保您的“NotFound”功能具有:

func NotFound(w http.ResponseWriter, r *http.Request) { // a * before http.Request


查看完整回答
反對 回復 2021-08-23
  • 2 回答
  • 0 關注
  • 270 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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