gin – 访问包含斜杠的URL编码路径参数的问题

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

gin - problem accessing url-encoded path-param containing forward slash

问题

对于给定的带有路径参数的路由(如下所示)

router.GET("/employee/:id", empHandler.GetEmployee)

当尝试调用包含斜杠的路径参数的URL时

id = 21/admin/527

URL编码的id = 21%2Fadmin%2F527

https://localhost:8000/emplayee/21%2Fadmin%2F527

当我尝试发送此请求时,我收到404错误。
看起来gin自动解码了路径参数并形成了一个包含解码后路径参数的URL。

https://localhost:8000/emplayee/21/admin/527

我想要的是员工ID路径参数的确切编码值,因为它将用于调用其他需要URL编码的API。

英文:

For a given route with path param (example below)

router.GET("/employee/:id", empHandler.GetEmployee)

When tried to invoke the url with id path-param(encoded) containing forward slashes

> id = 21/admin/527
>
> url-encoded id = 21%2Fadmin%2F527

https://localhost:8000/emplayee/21%2Fadmin%2F527

I'm getting 404 when I try to hit this request
It seems that gin is automatically decoding the path param and forming a route with url containing decoded path-param

https://localhost:8000/emplayee/21/admin/527

I want the exact encoded value for employee id path-param since it is to be used for calling other api which requires it to be url-encoded.

答案1

得分: 3

我已经通过以下选项配置路由器来解决了这个问题:

router.UseRawPath = true
router.UnescapePathValues = false

这解决了404错误,并且gin上下文返回相同的编码(未转义)值。
现在可以使用这个值调用其他需要员工ID的URL编码(未转义)值的API。

英文:

I've resolved this issue by configuring the router with below options

router.UseRawPath = true
router.UnescapePathValues = false

This resolved the 404 error, also gin context return the same encoded(unescaped) value.
This value can now be used to call the other APIs which requires url-encoded(unescaped) value for employee id

huangapple
  • 本文由 发表于 2022年3月23日 12:25:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/71581828.html
匿名

发表评论

匿名网友

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

确定