首页 > 解决方案 > 如何在中间件 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) 的情况下获取中间件内部的路由?

标签: gogo-chi

解决方案


基于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)
    })
})

推荐阅读