donglun4682 2012-04-03 15:43
浏览 83
已采纳

显示带有标准http包的自定义404错误页面

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.

  • 写回答

6条回答 默认 最新

  • doy2255 2012-04-03 21:00
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 哪个tomcat中startup一直一闪而过 找不出问题
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成