我正在尝试只在某些路由上添加一个中间件。我写了这段代码:
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)}
我希望只看到带有前缀/admin的路径的请求日志。当我执行"GET /admin“时,我确实看到了一个日志行,但当我执行"GET /admin/articles/new”时,我看不到日志行。我尝试了暴力其他组合,但我不能得到它。我的代码出了什么问题?
我看到了其他方法,比如在每个路由定义上包装HandlerFunc,但我想为前缀或子路由器包装一次。
我在那里使用的日志中间件用于测试,也许Auth中间件更有意义,但我只是想让它工作。
谢谢!
发布于 2017-06-22 04:24:33
问题在于创建子路由/admin的方式。完整的参考代码在这里https://play.golang.org/p/zb_79oHJed
// Admin
adminBase := mux.NewRouter()
router.PathPrefix("/admin").Handler(negroni.New(
// This logger only applicable to /admin routes
negroni.HandlerFunc(justTestLogger),
// add your handlers here which is only appilcable to `/admin` routes
negroni.Wrap(adminBase),
))
adminRoutes := adminBase.PathPrefix("/admin").Subrouter()
adminRoutes.HandleFunc("/articles/new", articleNewHandler).Methods("GET")现在,访问这些URL。您将只看到/admin子路由的日志。
https://stackoverflow.com/questions/44684788
复制相似问题