使用标准http包显示自定义404错误页面 [英] Showing custom 404 error page with standard http package
问题描述
假设我们有:
http.HandleFunc(/ smth,smthPage)
http.HandleFunc (/,homePage)
用户看到一个普通的404页面未找到错误的网址。
有关大猩猩/ mux的更新
如何返回该案例的自定义页面?
如果您使用gorilla / mux,您应该使用如下所示的内容: $ b
使用纯net / http软件包的用户可以接受的答案。$ b
func main(){
r:= mux.NewRouter()
r.NotFoundHandler = http.HandlerFunc(notFound)
$ b 并执行 func notFound(w http.ResponseWriter,r * http.Request)
。
解决方案我通常会这样做:
包主
导入(
fmt
净/ http
)
func main(){
http.HandleFunc(/,homeHandler)
http.HandleFunc(/ smth /,smthHandler)
http .ListenAndServe(:12345,无)
}
func homeHandler(w http.ResponseWriter,r * http.Request){
如果r.URL.Path!= /{
errorHandler(w, r,http.StatusNotFound)
return
}
fmt.Fprint(w,welcome home)
}
func smthHandler(w http。 ResponseWriter,r * http.Request){
如果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)
}
}
code> 这里我简化了代码,只显示了自定义的404,但实际上我做了更多的这个设置:我处理所有的HTTP错误与 errorHandler
,其中我记录有用的信息并发送给我自己的电子邮件。
Assuming that we have:
http.HandleFunc("/smth", smthPage)
http.HandleFunc("/", homePage)
User sees a plain "404 page not found" when they try a wrong URL. How can I return a custom page for that case?
Update concerning gorilla/mux
Accepted answer is ok for those using pure net/http package.
If you use gorilla/mux you should use something like this:
func main() {
r := mux.NewRouter()
r.NotFoundHandler = http.HandlerFunc(notFound)
}
And implement func notFound(w http.ResponseWriter, r *http.Request)
as you want.
I usually do this:
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")
}
}
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屋!