httprouter设置自定义NotFound

时间:2015-08-26 10:22:31

标签: go

我在Go项目中使用https://github.com/julienschmidt/httprouter

我问了一段时间这个问题是由@icza解决的:httprouter configuring NotFound但现在,启动一个新项目并使用非常相似的代码我似乎在控制台中出现错误。

尝试配置我正在使用的自定义处理程序NotFoundMethodNotAllowed

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
}

在过去的几个月里,这个软件包是否有一些重大变化,因为我无法弄清楚为什么我在一个项目中而不是另一个项目中出现错误?

1 个答案:

答案 0 :(得分:0)

自httprouter中提交70708e4600以来,router.NotFound不再是http.HandlerFunc而是http.Handler。因此,如果您使用最近提交的httprouter,则必须通过http://golang.org/pkg/net/http/#HandlerFunc调整您的函数。

以下内容应该有效(未经测试):

router.NotFound = http.HandlerFunc(customNotFound)