16

I just can't get this NotFoundHandler to work. I'd like to serve a static file on every get request, given that it exists, otherwise serve index.html. Here's my simplified router at the moment:

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 works ok

/file-that-exists works ok

/file-that-doesnt-exist doesn't work - I get 404 page not found instead of index.html

So what am I doing wrong here?

4

2 回答 2

35

问题是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)
于 2014-10-26T13:30:04.423 回答
4

这对我有用

r.NotFoundHandler = http.HandlerFunc(NotFound)

确保您的“未找到”功能具有:

func NotFound(w http.ResponseWriter, r *http.Request) { // a * before http.Request
于 2018-03-17T19:33:45.310 回答