【发布时间】: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
那么我在这里做错了什么?
【问题讨论】: