如何将中间件应用于Go Gorilla Toolkit多路复用器子路由器?
我有以下代码:
router := mux.NewRouter().StrictSlash(true) apiRouter := router.PathPrefix("/api/").Subrouter() apiRouter.Methods(http.MethodGet). Path("/api/path/to/handler").Handler(handleAPICall)
我想应用一个检查安全性令牌的中间件处理程序,但仅在以开头的那些路径上/api。
/api
以下似乎有效:
apiRouter := mux.NewRouter() router.PathPrefix("/api/").Handler(http.StripPrefix("/api", adapt(apiRouter, checkTokenHandler))) apiRouter.Methods(http.MethodGet). Path("/path/to/handler").Handler(handleAPICall) // Note that `/api` has been removed from the path.
哪里
func adapt(h http.Handler, adapters ...func(http.Handler) http.Handler) http.Handler { for _, adapter := range adapters { h = adapter(h) } return h }
和
func checkTokenHandler(h http.Handler) http.Handler { return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { // Check the security cookie. h.ServeHTTP(res, req) }) }