How to get route inside middleware go-chi

Issue

To check authorization i need to know the route inside the authorization middleware. I checked docs from go-chi and did it that way:

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
    }

    })
}

which gives me what I need.
But now obviously authorization is passed, so if check for routePattern, handler is already executed (wrote result to client)

Is there any other way to get the route inside of a middleware without next.ServerHTTP(w,r) before checking the RoutePattern()?

Solution

Resolved based on 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)
    })
})

Answered By – Stefan Wuthrich – Altafino

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.