要检查授权,我需要知道授权中间件内部的路由。我查了一下go的文档然后就这么做了:
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,就已经执行了处理程序(将结果写入客户端)。
在检查next.ServerHTTP(w,r)之前,有没有其他方法可以在没有RoutePattern()的情况下获取中间件内部的路由?
发布于 2018-10-11 11:51:57
基于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)
})
})https://stackoverflow.com/questions/52696109
复制相似问题