英文:
Gin Gonic - Literal colon inside the URL
问题
我正在使用Gin Gonic在Go语言中创建一些REST API。
我必须使用以下URL公开此端点:
/api/v1/action::request::export
我正在使用Gin Gonic创建路由,但是我遇到了错误“每个路径段只允许一个通配符”,因为冒号“:”用于映射URL中的参数。
有没有一种方法可以转义冒号“:”字符并在URL中使用它?
谢谢
英文:
I'm creating some REST API with Gin Gonic in go.
I have to expose this endpoint with this URL:
/api/v1/action::request::export
I'm using gin gonic to create the routes and I got this error "only one wildcard per path segment is allowed" because the colon ":" is used to map a parameters in the URL.
There is a way to escape the ":" character and use it into the URL?
Thanks
答案1
得分: 1
就像F.S在评论中提到的那样,你可以只使用一个路径参数action
,然后在代码中根据需要进行解析处理。
这是一个适用于你的示例:
package main
import (
"strings"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/api/v1/:action", func(c *gin.Context) {
params, ok := c.Params.Get("action")
if !ok {
// 处理错误
}
eachParam := strings.SplitN(params, ":", 3)
request, export := eachParam[1], eachParam[2] // 你实际的参数由":"分隔
c.JSON(200, gin.H{
"message": "good",
})
})
r.Run()
}
但是,当然,这种方法也有自己的注意事项,你必须自己处理异常和边界情况。
英文:
Like F.S mentioned in comment, you could use just one pathParam action
and then in code handle parsing as needed.
Here is an example that would work for you:
package main
import (
"strings"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/api/v1/:action", func(c *gin.Context) {
params, ok := c.Params.Get("action")
if !ok {
// handle error
}
eachParam := strings.SplitN(params, ":", 3)
request, export := eachParam[1], eachParam[2] // your actual params divided by ":"
c.JSON(200, gin.H{
"message": "good",
})
})
r.Run()
}
But of course, this approach have its own caveats, you have to handle exceptions and edge cases yourself.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论