0
我想只在一些路由上添加一个中间件。我写了这个代码:Subroutes中间件与大猩猩MUX和Negroni
func main() {
router := mux.NewRouter().StrictSlash(false)
admin_subrouter := router.PathPrefix("/admin").Subrouter()
//handlers.CombinedLoggingHandler comes from gorilla/handlers
router.PathPrefix("/admin").Handler(negroni.New(
negroni.Wrap(handlers.CombinedLoggingHandler(os.Stdout, admin_subrouter)),
))
admin_subrouter.HandleFunc("/articles/new", articles_new).Methods("GET")
admin_subrouter.HandleFunc("/articles", articles_index).Methods("GET")
admin_subrouter.HandleFunc("/articles", articles_create).Methods("POST")
n := negroni.New()
n.UseHandler(router)
http.ListenAndServe(":3000", n)
}
我希望看到的请求日志只能用于前缀/管理路径。当我做“GET/admin”时,我确实看到了一条日志行,但当我做“GET/admin/articles/new”时没有看到。我试图通过蛮力其他组合,但我无法得到它。我的代码有什么问题?
我看到了其他方式,比如在每个路由定义上包装HandlerFunc,但是我想为前缀或子路由器执行一次。
我在那里使用的日志记录中间件用于测试,也许一个Auth中间件更有意义,但我只是想让它工作。
谢谢!
工作,谢谢。我想使用Gorilla包处理程序中提供的中间件。 –
然后,我能够用大猩猩做处理。 'router.PathPrefix( “/ admin” 的)处理程序(negroni.New( \t negroni.Wrap(handlers.CombinedLoggingHandler(os.Stdout,adminBase)), \t)) ' –
是的,你可以使用它,只是为了演示子路由器的定义,我没有在例子中使用它。对于那个很抱歉。 – jeevatkm