httprouter配置NotFound [英] httprouter configuring NotFound
问题描述
我使用 httprouter
作为API和我试图找出如何处理404s。它确实在文档中说过404可以手动处理,但我不会'我真的不知道如何编写自己的自定义处理程序。
我在其他路线后尝试了以下内容...
router.NotFound(pageNotFound)
但是我在调用router.NotFound 时收到错误没有足够的参数。
/godoc.org/github.com/julienschmidt/httprouter#Routerrel =nofollow>
httprouter.Router
是结构
有一个字段: NotFound http.HandlerFunc
因此 NotFound
是 http.Han
类型HandlerFunc func(ResponseWriter,*请求)
如果你想要自己定制的Not Found处理程序,你必须设置一个函数值与上面的签名。
例如:
func MyNotFound w http.ResponseWriter,r * http.Request){
w.Header()。Set(Content-Type,text / plain; )
w.WriteHeader(http.StatusNotFound)// StatusNotFound = 404
w.Write([] byte(My own Not Found handler。))
w.Write([] byte(您请求的页面无法找到。))
}
var router * httprouter.Router = ... //您的路由器值
router.NotFound = MyNotFound
NotFound
函数将被 httprouter
包调用,如果你想从你的其他处理程序手动调用它,你必须通过 ResponseWriter
和 *请求
,如下所示:
func ResourceHandler(w http.ResponseWriter,r * http.Request){
exists:= ... // Find out如果请求的资源有效且可用
if!exists {
MyNotFound(w,r)// Pas s ResponseWriter和Request
//或通过路由器:
// router.NotFound(w,r)
return
}
//资源存在,为它服务
// ...
}
I'm using httprouter
for an API and I'm trying to work out how to handle 404s. It does say in the docs that 404's can be handled manually but I don't really have an idea how to write my own custom handler.
I've tried the following after my other routes...
router.NotFound(pageNotFound)
But I get the error not enough arguments in call to router.NotFound
.
If anyone could point me in the right direction it would be great.
The type httprouter.Router
is a struct
which has a field:
NotFound http.HandlerFunc
So NotFound
is an http.HandlerFunc
, a function type with signature:
type HandlerFunc func(ResponseWriter, *Request)
If you want your own custom "Not Found" handler, you have to set a function value with the signature above.
For example:
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 = MyNotFound
This NotFound
function will be invoked by the httprouter
package. If you would want to call it manually from one of your other handlers, you would have to pass a ResponseWriter
and a *Request
to it, something like this:
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
// ...
}
这篇关于httprouter配置NotFound的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!