我试图仅在某些路由上添加中间件。我写了这段代码:
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 中间件更有意义,但我只是想让它工作。
谢谢!