httprouter配置NotFound

tom*_*456 4 http url-routing go

我正在使用httprouterAPI,我正试图找出如何处理404s.它确实在文档中说404可以手动处理,但我真的不知道如何编写自己的自定义处理程序.

在我的其他路线之后我尝试了以下内容......

router.NotFound(pageNotFound)
Run Code Online (Sandbox Code Playgroud)

但是我得到了错误not enough arguments in call to router.NotFound.

如果有人能指出我正确的方向,那将是伟大的.

icz*_*cza 7

类型httprouter.Router是一个struct有一个字段:

NotFound http.Handler
Run Code Online (Sandbox Code Playgroud)

所以类型NotFoundhttp.Handler一种接口类型,它有一个方法:

ServeHTTP(ResponseWriter, *Request)
Run Code Online (Sandbox Code Playgroud)

如果您需要自己的自定义"Not Found"处理程序,则必须设置实现此接口的值.

最简单的方法是使用签名定义函数:

func(http.ResponseWriter, *http.Request)
Run Code Online (Sandbox Code Playgroud)

并使用http.HandlerFunc()辅助函数将其"转换"为实现http.Handler接口的值,其ServeHTTP()方法只是使用上述签名调用函数.

例如:

func MyNotFound(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    w.WriteHeader(http.StatusNotFound) // StatusNotFound = 404
    w.Write([]byte("My own Not Found handler."))
    w.Write([]byte(" The page you requested could not be found."))
}

var router *httprouter.Router = ... // Your router value
router.NotFound = http.HandlerFunc(MyNotFound)
Run Code Online (Sandbox Code Playgroud)

NotFound将调用此处理httprouter程序.如果您想要从其他处理程序手动调用它,则必须将a ResponseWriter和a 传递*Request给它,如下所示:

func ResourceHandler(w http.ResponseWriter, r *http.Request) {
    exists := ... // Find out if requested resource is valid and available
    if !exists {
        MyNotFound(w, r) // Pass ResponseWriter and Request
        // Or via the Router:
        // router.NotFound(w, r)
        return
    }

    // Resource exists, serve it
    // ...
}
Run Code Online (Sandbox Code Playgroud)