类型
httprouter.Router是
struct具有字段的:
NotFound http.Handler
因此,类型为,
NotFound是
http.Handler一种具有单个方法的接口类型:
ServeHTTP(ResponseWriter, *Request)
如果要使用自己的自定义“未找到”处理程序,则必须设置一个实现此接口的值。
最简单的方法是使用签名定义函数:
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 valuerouter.NotFound = http.HandlerFunc(MyNotFound)该
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 // ...}


