我试图只在某些路由上添加中间件。我写了这段代码:
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 中间件更有意义,但我只是想让它工作。
谢谢!
最佳答案
问题是您创建子路由 /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
子路由的日志。
关于go - 使用 Gorilla MUX 和 Negroni 的子路由中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44684788/