英文:
In go, how do I use a closure with a gorilla/mux subrouter?
问题
这里有很多类似于这个链接中使用HandlerFunc闭包的示例:http://codegangsta.gitbooks.io/building-web-apps-with-go/content/controllers/README.html
然而,我无法将其与子路由一起使用。例如:
func MyHandler(renderer *render.Render) http.Handler {
    return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
        renderer.HTML(rw, http.StatusOK, "subroute/index", nil)
    })
}
func main() {
    renderer := render.New(render.Options{Layout: "base"})
    router := mux.NewRouter().StrictSlash(false)
    
    router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        ...
    })
    subroutes := router.Path("/subroute").Subrouter()
    subroutes.Methods("GET").HandlerFunc(MyHandler(renderer))
    http.Handle("/", router)
    log.Println("Listening...")
    http.ListenAndServe(":3000", nil)
}
给我返回了这个错误:
cannot use MyHandler(renderer) (type http.Handler) as type func(http.ResponseWriter, *http.Request) in function argument
对于我做错了什么,有什么见解吗?
英文:
There seem to be all sorts of examples of using a HandlerFunc closure similar to this one: http://codegangsta.gitbooks.io/building-web-apps-with-go/content/controllers/README.html
However I can't get it to work with a subrouter. Example:
func MyHandler(renderer *render.Render) http.Handler {
    return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
        renderer.HTML(rw, http.StatusOK, "subroute/index", nil)
    })
}
func main() {
    renderer := render.New(render.Options{Layout: "base"})
    router := mux.NewRouter().StrictSlash(false)
    
    router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        ...
    })
    subroutes := router.Path("/subroute").Subrouter()
    subroutes.Methods("GET").HandlerFunc(MyHandler(renderer))
    http.Handle("/", router)
    log.Println("Listening...")
    http.ListenAndServe(":3000", nil)
}
Gives me this error:
cannot use MyHandler(renderer) (type http.Handler) as type func(http.ResponseWriter, *http.Request) in function argument
Any insights into what I'm doing wrong?
答案1
得分: 3
Route上的HandlerFunc方法期望传递一个函数,正如错误消息所指示的那样。如果你有一个http.Handler,则调用Handler:
subroutes.Methods("GET").Handler(MyHandler(renderer))
或者,让你的MyHandler函数直接返回处理程序函数,而不是将其包装为http.Handler。选择哪个选项将取决于你的编程风格和程序的其他部分。
英文:
The HandlerFunc method on Route expects to be passed a function, as the error message indicates.  If instead you have an http.Handler, call Handler instead:
subroutes.Methods("GET").Handler(MyHandler(renderer))
Or alternatively, have your MyHandler function return the handler function directly rather than wrapping it as an http.Handler.  Which option you choose is going to be a matter of style, and depend on the rest of your program.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论