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条)

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真