如何在中间件go-chi中获取路由
How to get route inside middleware go-chi
要检查授权,我需要知道授权中间件内的路由。我检查了 go-chi 的文档并这样做了:
func Authenticator(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// .............
next.ServeHTTP(w, r)
routePattern := chi.RouteContext(r.Context()).RoutePattern()
fmt.Println("AUTHORIZATION:", routePattern, route)
routepath := strings.Replace(routePattern, "/v1", "", 1) // todo use api prefix from config
routepath = strings.Replace(routepath, "/*", "", 1)
fmt.Println("ROUTEPATH:", routepath, route)
if !CheckAuthorization(*token, routepath, method, "*", "*", "*") {
http.Error(w, http.StatusText(401), 401)
return
}
})
}
这给了我我需要的东西。
但是现在显然已经通过了授权,所以如果检查 routePattern
,处理程序已经执行(将结果写入客户端)
在检查 RoutePattern()
之前,有没有其他方法可以在没有 next.ServerHTTP(w,r)
的情况下获取中间件内部的路由?
根据https://medium.com/@szablowska.patrycja/chi-and-missing-urlparam-in-middleware-9435c48a063b
解决
r := chi.NewRouter()
r.Route("/myroute", func(r chi.Router) {
r.With(myMiddleware).Route("/{myparam}", func(r chi.Router) {
r.Get("/", getHandler)
r.Put("/", putHandler)
})
})
要检查授权,我需要知道授权中间件内的路由。我检查了 go-chi 的文档并这样做了:
func Authenticator(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// .............
next.ServeHTTP(w, r)
routePattern := chi.RouteContext(r.Context()).RoutePattern()
fmt.Println("AUTHORIZATION:", routePattern, route)
routepath := strings.Replace(routePattern, "/v1", "", 1) // todo use api prefix from config
routepath = strings.Replace(routepath, "/*", "", 1)
fmt.Println("ROUTEPATH:", routepath, route)
if !CheckAuthorization(*token, routepath, method, "*", "*", "*") {
http.Error(w, http.StatusText(401), 401)
return
}
})
}
这给了我我需要的东西。
但是现在显然已经通过了授权,所以如果检查 routePattern
,处理程序已经执行(将结果写入客户端)
在检查 RoutePattern()
之前,有没有其他方法可以在没有 next.ServerHTTP(w,r)
的情况下获取中间件内部的路由?
根据https://medium.com/@szablowska.patrycja/chi-and-missing-urlparam-in-middleware-9435c48a063b
解决r := chi.NewRouter()
r.Route("/myroute", func(r chi.Router) {
r.With(myMiddleware).Route("/{myparam}", func(r chi.Router) {
r.Get("/", getHandler)
r.Put("/", putHandler)
})
})