dpepbjp126917 2015-08-26 10:22
浏览 140
已采纳

httprouter设置自定义NotFound

I'm using https://github.com/julienschmidt/httprouter in my Go project.

I asked this question a while back which was solved by @icza: httprouter configuring NotFound but now, starting a new project and using very similar code I appear to be getting errors in the console.

Trying to configure custom handlers NotFound and MethodNotAllowed I'm using:

router.NotFound = customNotFound
router.MethodNotAllowed = customMethodNotAllowed

produces:

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)  

My functions look like this:

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
}

Has there been some breaking changes in this package in the last couple of months as I can't work out why I'm getting the error in one project and not in the other?

  • 写回答

1条回答 默认 最新

  • dqpfkzu360216 2015-08-26 11:24
    关注

    Since commit 70708e4600 in httprouter the router.NotFound is no longer a http.HandlerFunc but a http.Handler. So you will have to adapt your functions with via http://golang.org/pkg/net/http/#HandlerFunc if you use a recent commit of httprouter.

    The following should work (untested):

    router.NotFound = http.HandlerFunc(customNotFound)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料