How to get route inside middleware go-chi

6.2k views Asked by At

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()?

1

There are 1 answers

0
Stefan Wuthrich - Altafino On BEST ANSWER

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