【发布时间】:2019-02-24 18:38:50
【问题描述】:
我正在使用 Go 构建一个小型网站,但遇到了自定义 404 页面的问题。这是我当前的路由器代码:
r := mux.NewRouter()
// Page routing
r.HandleFunc("/", homeHandler).Methods("GET")
r.HandleFunc("/example1", exampleOneHandler).Methods("GET")
r.HandleFunc("/example2", exampleTwoHandler).Methods("GET", "POST")
// Other paths for static assets omitted
// Psuedo-root directory for icon files, etc.
r.PathPrefix("/").Handler(http.FileServer(http.Dir("public")))
// 404 Page
r.NotFoundHandler = http.HandlerFunc(notFoundHandler)
log.Fatal(http.ListenAndServe(":1234", r))
因此,如果没有第 11 行的 PathPrefix 定义,notFoundHandler 会按预期命中并返回自定义 404 HTML。
但是,现在我添加了该路径定义以适应根目录标准,例如 favicon.ico、robots.txt、应用程序图标等,并且可以按预期工作。然而,作为副作用,任何与 /example1 或 /example2 不匹配的东西,比如 /example3,都会通过 http.FileServer 在伪根目录中查找名为“example3”的文件。没有找到后,FileServer 直接写入 http.ResponseWriter 并以“404 not found”,完全绕过 mux 的 NotFoundHandler。
我能看到的唯一可行的解决方案是为每个文件添加一个明确的路由,但这似乎是一个相当残酷的解决方案。有没有更优雅的方法来解决我缺少的这个问题?
【问题讨论】:
标签: go routing http-status-code-404 mux