在使用过程中,如何将封闭与大猩猩/多路复用子路由器一起使用?
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?
似乎有使用HandlerFunc闭包的各种示例,类似于以下示例: http://codegangsta.gitbooks.io/building-web-apps-with -go / content / controllers / README.html p>
但是我无法将其与子路由器一起使用。 示例: p>
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”})
路由器:= mux.NewRouter()。StrictSlash(false)
router.HandleFunc(“ /”,func(w http.ResponseWriter,r * http.Request){
.. 。
})
子路由:= router.Path(“ / subroute”)。Subrouter()
子路由.Methods(“ GET”)。HandlerFunc(MyHandler(renderer))
http.Handle (“ /”,路由器)
log.Println(“ Listening ...”)
http.ListenAndServe(“:3000”,nil)
}
code> pre>
给我这个错误: p>
不能在其中使用MyHandler(renderer)(类型为http.Handler)作为func(http.ResponseWriter,* http.Request)类型 函数参数
code> pre>
对我在做什么的任何见解? p>
div>
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.