You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi I am migrating from an echo router codebase to chi. One of the things we use was the parameterised path variable echo provides. I can see a similar thing in chi, chi.RouteContext(r.Context()).RoutePattern(), but this function seems to be returning an empty string when called in middlewares. Is there way out?
@jutkko the RoutePattern() will only return a value once its determined the final route. You can either access it in the endpoint handler, or after a request responds in the middleware. See the description in https://github.com/go-chi/chi/blob/master/context.go#L80-L93 and example there:
For anyone who still needs this, the following seems to work:
funcgetRoutePattern(r*http.Request) string {
rctx:=chi.RouteContext(r.Context())
ifpattern:=rctx.RoutePattern(); pattern!="" {
// Pattern is already availablereturnpattern
}
routePath:=r.URL.Pathifr.URL.RawPath!="" {
routePath=r.URL.RawPath
}
tctx:=chi.NewRouteContext()
if!rctx.Routes.Match(tctx, r.Method, routePath) {
// No matching pattern, so just return the request path.// Depending on your use case, it might make sense to// return an empty string or error here insteadreturnroutePath
}
// tctx has the updated pattern, since Match mutates itreturntctx.RoutePattern()
}
Reacted by Redha Juanda, Julien Ammous, Leigh, Alexandre, Chris, Sean Gosiaco, Gildson, Junpei Tsuji, Alexander Menshchikov, Amarjeet Singh Rai and 2 more
Reacted by Leigh, Daria, Gildson, Hafiz Shafruddin, Stefano Arlandini, Maksim Ivanov, Amarjeet Singh Rai and Attila Sumi
Activity
pkieltyka commentedon Oct 10, 2017
@jutkko the RoutePattern() will only return a value once its determined the final route. You can either access it in the endpoint handler, or after a request responds in the middleware. See the description in https://github.com/go-chi/chi/blob/master/context.go#L80-L93 and example there:
please let me know if this works for you guys / other feedback
jutkko commentedon Oct 10, 2017
Yes that will do the job. But there are some operations (tracing) we want to do before calling
nextand also want to have theRoutePattern()...Thanks for the quick response though!
pkieltyka commentedon Oct 10, 2017
@jutkko cool - if thats the case, you could use a technique similar in https://github.com/go-chi/chi/blob/master/middleware/get_head.go to pre-process the route and get the RoutePattern() from that context.
rafaeljesus commentedon Aug 23, 2018
Hi @pkieltyka I didn't understand well the pre-process tip you gave? I tried here having 2 middleware:
NewRoutePatternNewTraceRequestAny thoughts? Thanks
rliebz commentedon Apr 2, 2019
For anyone who still needs this, the following seems to work: