简体   繁体   English

go chi 将子路由路径视为 881657866602088 参数

[英]go chi treating sub route path as URL param

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下面是我的 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.但是在 GetProducts 处理程序 function 中,当我从请求上下文中获取所有 url 参数时,url 参数*正在映射到不是 URL 参数的路径product Below is the code snippet of the GetProducts handler下面是 GetProducts 处理程序的代码片段

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当使用路由 /val1/val2/dummy/new/product 调用 url 时,上面 for 循环中的 output 是

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.无法理解为什么 * 被映射到产品,尽管它是一个子路由而不是 URL 参数。 Couldn't find any reference on related issue.找不到相关问题的任何参考。

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.这里的问题似乎是我使用的 package 的版本,我使用的是 github.com/go-chi/chi v4.1.2 和 go1.17,我在那里遇到了这个问题。 Migrating to github.com/go-chi/chi/v5 v5.0.0 solved the issue.迁移到 github.com/go-chi/chi/v5 v5.0.0 解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM