我在Go项目中使用https://github.com/julienschmidt/httprouter。
不久前我问了这个问题,该问题由@icza解决:httprouter configuring NotFound,但是现在,开始一个新项目并使用非常相似的代码,似乎在控制台中出现错误。
尝试配置我正在使用的自定义处理程序NotFound
和MethodNotAllowed
:
router.NotFound = customNotFound
router.MethodNotAllowed = customMethodNotAllowed
产生:
cannot use customNotFound (type func(http.ResponseWriter, *http.Request)) as type http.Handler in assignment:
func(http.ResponseWriter, *http.Request) does not implement http.Handler (missing ServeHTTP method)
cannot use customMethodNotAllowed (type func(http.ResponseWriter, *http.Request)) as type http.Handler in assignment:
func(http.ResponseWriter, *http.Request) does not implement http.Handler (missing ServeHTTP method)
我的函数如下所示:
func customNotFound(w http.ResponseWriter, r *http.Request) {
core.WriteError(w, "PAGE_NOT_FOUND", "Requested resource could not be found")
return
}
func customMethodNotAllowed(w http.ResponseWriter, r *http.Request) {
core.WriteError(w, "METHOD_NOT_PERMITTED", "Request method not supported by that resource")
return
}
在过去的几个月中,此程序包中发生了一些重大更改,因为我无法弄清楚为什么我在一个项目中却在另一个项目中却没有错误?
最佳答案
自从在httprouter中提交70708e4600以来,router.NotFound
不再是http.HandlerFunc
而是http.Handler
。因此,如果使用最近提交的httprouter,则必须通过http://golang.org/pkg/net/http/#HandlerFunc调整功能。
以下应该工作(未试用):
router.NotFound = http.HandlerFunc(customNotFound)