go chi treating sub route path as URL param

788 views Asked by At

i am creating a base router and adding few middlewares and health check route as below

baseRouter := chi.NewRouter()
baseRouter.Use(middleware.Logger)
baseRouter.Use(core.CorsHandler)
baseRouter.Get("/", func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Context-Type", "text/plain")
    w.Write([]byte("Up and Running!!"))
})

then i am mounting my sub-routes on the base router as

baseRouter.Route("/{param1}/{param2}/dummy/new", func(r chi.Router) {
    productHandler.MountRoutes(r)
})

and below is my productHandler.MountRoutes function

func (h Handler) MountRoutes(r chi.Router) {

    r.MethodFunc(http.MethodGet, "/product/report/{report_id}", h.ExportStatus)
    r.MethodFunc(http.MethodPost, "/product/report", h.ExportProducts)
    r.MethodFunc(http.MethodPost, "/product", h.GetProducts)
}

but in the GetProducts handler function, when i fetch all the url parameters from the request context, the url param * is getting mapped to the path product which is not a URL param. Below is the code snippet of the GetProducts handler

ctx := context.WithValue(r.Context(), "var1", 0)
routeCtx := chi.RouteContext(ctx)
urlKeys := routeCtx.URLParams.Keys
for _, param := range urlKeys {
    parsedParam := chi.URLParam(r, param)
    fmt.Printf("%s - %s\n", param, parsedParam)
}

the output from the above for loop when calling the url with route /val1/val2/dummy/new/product is

param1 - val1
param2 - val2
*      - product

couldn't get why the * is getting mapped to the product eventhough its a sub-route and not a URL param. Couldn't find any reference on related issue.

1

There are 1 answers

0
vignesh On

The issue here seems to be the version of the package i was using, i was using github.com/go-chi/chi v4.1.2 with go1.17 where i was getting this issue. Migrating to github.com/go-chi/chi/v5 v5.0.0 solved the issue.