方式httprouter.Router is a struct
其中有一个字段:
NotFound http.Handler
所以类型NotFound
is http.Handler,具有单个方法的接口类型:
ServeHTTP(ResponseWriter, *Request)
如果您想要自己的自定义“Not Found”处理程序,则必须设置一个实现此接口的值。
最简单的方法是定义一个带签名的函数:
func(http.ResponseWriter, *http.Request)
并使用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)
This NotFound
处理程序将被调用httprouter
包裹。如果您想从其他处理程序之一手动调用它,则必须传递一个ResponseWriter and 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
// ...
}