doushui5587 2014-09-17 10:12
浏览 45
已采纳

如何在MuxChain中使用HttpRouter?

I'd like to use httprouter with muxchain while keeping route parameters like /:user/.

Take the following example:

func log(res http.ResponseWriter, req *http.Request) {
  fmt.Println("some logger")
}

func index(res http.ResponseWriter, req *http.Request) {
  fmt.Fprintf(res, "Hi there, I love %s!", req.URL.Path[1:])
}

func main() {
  logHandler := http.HandlerFunc(log)
  indexHandler := http.HandlerFunc(index)
  chain := muxchain.ChainHandlers(logHandler, indexHandler)
  router := httprouter.New()
  router.Handler("GET", "/:user", chain)
  http.ListenAndServe(":8080", router)
}

When I visit http://localhost:8080/john I obviously don't have access to ps httprouter.Params That's because httprouter needs to see type httprouter.Handle but the function is called with type http.Handler.

Is there any way to use both packages together? The HttpRouter GitHub repo says

The only disadvantage is, that no parameter values can be retrieved when a http.Handler or http.HandlerFunc is used, since there is no efficient way to pass the values with the existing function parameters.

  • 写回答

2条回答 默认 最新

  • dongyuan9892 2014-09-17 12:28
    关注

    You would have to patch muxchain to accept httprouter.Handle, but it's rather simple to create your own chain handler, for example:

    func chain(funcs ...interface{}) httprouter.Handle {
        return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
            for _, h := range funcs {
                switch h := h.(type) {
                case httprouter.Handle:
                    h(w, r, p)
                case http.Handler:
                    h.ServeHTTP(w, r)
                case func(http.ResponseWriter, *http.Request):
                    h(w, r)
                default:
                    panic("wth")
                }
    
            }
        }
    }
    

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效