显示带有标准 http 包的自定义 404 错误页面 [英] Showing custom 404 error page with standard http package
问题描述
假设我们有:
http.HandleFunc("/smth", smthPage)
http.HandleFunc("/", homePage)
当用户尝试错误的 URL 时,他们会看到一个简单的404 页面未找到".我如何为这种情况返回自定义页面?
User sees a plain "404 page not found" when they try a wrong URL. How can I return a custom page for that case?
关于 gorilla/mux 的更新
对于那些使用纯 net/http 包的人来说,接受的答案是可以的.
Accepted answer is ok for those using pure net/http package.
如果你使用 gorilla/mux,你应该使用这样的东西:
If you use gorilla/mux you should use something like this:
func main() {
r := mux.NewRouter()
r.NotFoundHandler = http.HandlerFunc(notFound)
}
并根据需要实现 func notFound(w http.ResponseWriter, r *http.Request)
.
推荐答案
我通常这样做:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/smth/", smthHandler)
http.ListenAndServe(":12345", nil)
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
errorHandler(w, r, http.StatusNotFound)
return
}
fmt.Fprint(w, "welcome home")
}
func smthHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/smth/" {
errorHandler(w, r, http.StatusNotFound)
return
}
fmt.Fprint(w, "welcome smth")
}
func errorHandler(w http.ResponseWriter, r *http.Request, status int) {
w.WriteHeader(status)
if status == http.StatusNotFound {
fmt.Fprint(w, "custom 404")
}
}
这里我已经将代码简化为仅显示自定义 404,但实际上我对这个设置做了更多的事情:我使用 errorHandler
处理所有 HTTP 错误,我在其中记录有用的信息并发送电子邮件给我自己.
Here I've simplified the code to only show custom 404, but I actually do more with this setup: I handle all the HTTP errors with errorHandler
, in which I log useful information and send email to myself.
这篇关于显示带有标准 http 包的自定义 404 错误页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!