'How to get route inside middleware go-chi

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 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stefan Wuthrich - Altafino