public 的 httprouter 和 negroni 以及私有路由中间件
httprouter and negroni for public and private routing middleware
我很难理解如何一起使用 negroni 和 httprouter。
我有几条 public 路线,例如 /api/v1/ping
我有一堆私有路由需要auth中间件,比如/api/v1/user
如果我想为我的所有路由使用 negroni 通用中间件,但我只想将 auth 中间件和其他中间件应用于私有路由,我该如何设置?
v1.router := httprouter.New()
v1.router.GET("/api/v1/ping", v1.ping)
v1.router.GET("/api/v1/user", v1.getUsers)
n := negroni.Classic()
n.UseHandler(v1.router)
http.ListenAndServe(port, n)
您也可以尝试调整“Path Prefix Middleware in Go ", which is using net/http/#ServeMux
, with another router (gorilla/mux
), but should be valid for julienschmidt/httprouter
中描述的技术:
Specifying middleware based on route prefixes
This is where the magic happens, and it is also where things get confusing.
The easiesy way I have found to specify middleware for a path prefix is to setup a second muxer (we use the sirMuxalot
variable for ours below) that has the path prefixes we want to apply middleware to, and to then pass in our original router wrapped in some middleware for those routes.
This works because the sirMuxalot
router won’t ever call the middleware-wrapped router unless the path prefix we define gets matched with the incoming web request’s path.
sirMuxalot := http.NewServeMux()
sirMuxalot.Handle("/", r)
sirMuxalot.Handle("/api/", negroni.New(
negroni.HandlerFunc(APIMiddleware),
negroni.Wrap(r),
))
sirMuxalot.Handle("/dashboard/", negroni.New(
negroni.HandlerFunc(DashboardMiddleware),
negroni.Wrap(r),
))
n := negroni.Classic()
n.UseHandler(sirMuxalot)
http.ListenAndServe(":3000", n)
我很难理解如何一起使用 negroni 和 httprouter。
我有几条 public 路线,例如 /api/v1/ping
我有一堆私有路由需要auth中间件,比如/api/v1/user
如果我想为我的所有路由使用 negroni 通用中间件,但我只想将 auth 中间件和其他中间件应用于私有路由,我该如何设置?
v1.router := httprouter.New()
v1.router.GET("/api/v1/ping", v1.ping)
v1.router.GET("/api/v1/user", v1.getUsers)
n := negroni.Classic()
n.UseHandler(v1.router)
http.ListenAndServe(port, n)
您也可以尝试调整“Path Prefix Middleware in Go ", which is using net/http/#ServeMux
, with another router (gorilla/mux
), but should be valid for julienschmidt/httprouter
中描述的技术:
Specifying middleware based on route prefixes
This is where the magic happens, and it is also where things get confusing.
The easiesy way I have found to specify middleware for a path prefix is to setup a second muxer (we use the
sirMuxalot
variable for ours below) that has the path prefixes we want to apply middleware to, and to then pass in our original router wrapped in some middleware for those routes.This works because the
sirMuxalot
router won’t ever call the middleware-wrapped router unless the path prefix we define gets matched with the incoming web request’s path.sirMuxalot := http.NewServeMux() sirMuxalot.Handle("/", r) sirMuxalot.Handle("/api/", negroni.New( negroni.HandlerFunc(APIMiddleware), negroni.Wrap(r), )) sirMuxalot.Handle("/dashboard/", negroni.New( negroni.HandlerFunc(DashboardMiddleware), negroni.Wrap(r), )) n := negroni.Classic() n.UseHandler(sirMuxalot) http.ListenAndServe(":3000", n)