我们不能在Gorilla子路由器的路径前缀中包含变量吗?

huangapple go评论83阅读模式
英文:

Can't we include vars in gorilla subrouter pathprefix?

问题

我正在尝试将子路由添加到我的路由器代码中:

router := mux.NewRouter()
baseRouter := router.PathPrefix("/api/v1").Subrouter()
managementRouter := baseRouter.PathPrefix("/managing/{id}").Subrouter()
managementRouter.Use(auth.ManagingMiddleware)
managementRouter.HandleFunc("/add-employees", management.AddEmployeesToOrganization).Methods("POST")

目标是强制客户端在每次调用managementRouter函数时提供一个id变量。
然而,当我发送这样的请求时:

/api/v1/managing/627e6f7e05db3552970e1164/add-employees

...我得到一个404错误。我是否遗漏了什么,或者这根本不可能实现?

英文:

I'm trying to add a subrouter to my router code :

router := mux.NewRouter()
baseRouter := router.PathPrefix("/api/v1").Subrouter()
managementRouter := baseRouter.PathPrefix("/managing/{id}").Subrouter()
managementRouter.Use(auth.ManagingMiddleware)
managementRouter.HandleFunc("/add-employees", management.AddEmployeesToOrganization).Methods("POST")

The goal is to force the client to give an id variable on each call to managementRouter
functions.
Although, when i send a request like this :

/api/v1/managing/627e6f7e05db3552970e1164/add-employees

... I get a 404. Am I missing something or is it just not possible ?

答案1

得分: 0

好的,以下是翻译好的内容:

好的,所以昨晚我在梦中找到了一个解决方案,哈哈

基本上,以下前缀的问题是:

managementRouter := baseRouter.PathPrefix("/managing/{id}").Subrouter()

问题在于路由器无法知道id字段的结束位置。因此,当我们访问一个端点时,例如这个URL:/api/v1/managing/627e6f7e05db3552970e1164/add-employees,路由器会认为{id}变量实际上是627e6f7e05db3552970e1164/add-employees,并且不匹配之后的任何路由。

所以我找到的解决方案是告诉路由器变量之后的内容。为此,你只需在变量后面添加一个斜杠:

managementRouter := baseRouter.PathPrefix("/managing/{id}/").Subrouter()
英文:

Ok so I found a solution in my dream last night haha

Basically the problem with the following prefix :

managementRouter := baseRouter.PathPrefix("/managing/{id}").Subrouter()

Is that the router has no way of knowing where the id field stops. So when we access an endpoint with for example this url : /api/v1/managing/627e6f7e05db3552970e1164/add-employees, the router believes that the {id} variable is literally 627e6f7e05db3552970e1164/add-employees and doesn't match any route after it.

So the solution I found is to tell the router what comes after the variable. For that, you just add a slash after the variable :

managementRouter := baseRouter.PathPrefix("/managing/{id}/").Subrouter()

huangapple
  • 本文由 发表于 2022年5月13日 23:57:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/72232361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定