【问题标题】:Go and Gorilla Mux NotFoundHandler not workingGo 和 Gorilla Mux NotFoundHandler 不工作
【发布时间】:2014-12-21 19:05:17
【问题描述】:

我就是无法让这个 NotFoundHandler 工作。如果它存在,我想在每个获取请求上提供一个静态文件,否​​则提供 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 page not found 而不是 index.html

那么我在这里做错了什么?

【问题讨论】:

    标签: go mux gorilla


    【解决方案1】:

    这对我有用

    r.NotFoundHandler = http.HandlerFunc(NotFound)
    

    确保您的“未找到”函数具有:

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

    【讨论】:

      【解决方案2】:

      问题是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)
      

      【讨论】:

      • 如果请求没有到达任何处理程序并且我们收到错误的响应请求怎么办?有没有办法测试那个场景?
      猜你喜欢
      • 2018-08-27
      • 2015-05-03
      • 2015-04-02
      • 2015-04-18
      • 2022-01-20
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多