使用Rails的路由,对于
https://www.amazon.com/posts/1
这样的URL,可以用这样的方式来做
get 'posts/:url', to: 'posts#search', constraints: { url: /.*/ }
使用go的gin框架,没有找到这样的路由的正则约束方法
r.GET("posts/search/:url", post.Search)
在后置控制器中
func Search(c *gin.Context) {
fmt.Println(c.Param("url"))
}
调用
http://localhost:8080/posts/search/https://www.amazon.com/posts/1
时,返回404代码。
喜欢https://play.golang.org/p/dsB-hv8Ugtn
➜ ~ curl http://localhost:8080/site/www.google.com
Hello www.google.com%
➜ ~ curl http://localhost:8080/site/http://www.google.com/post/1
404 page not found%
➜ ~ curl http://localhost:8080/site/https%3A%2F%2Fwww.google.com%2Fpost%2F1
404 page not found%
➜ ~ curl http://localhost:8080/site/http:\/\/www.google.com\/post\/1
404 page not found%
Gin 不支持路由器中的正则表达式。这可能是因为它构建了路径树,以便在遍历时不必分配内存并获得出色的性能。
对路径的参数支持也不是很强大,但您可以通过使用像
这样的可选参数来解决这个问题c.GET("/posts/search/*url", ...)
现在
c.Param("url")
可以包含斜杠。但还有两个未解决的问题:
Gin 的路由器会解码百分比编码字符 (%2F),因此如果原始 URL 具有此类编码部分,则会错误地最终解码并且与您想要提取的原始 URL 不匹配。请参阅相应的 Github 问题:https://github.com/gin-gonic/gin/issues/2047
您只能在参数中获得 URL 的 schema+host+path 部分,查询字符串仍然是单独的,除非您也对其进行编码。例如。
/posts/search/http://google.com/post/1?foo=bar
会给你一个 "/http://google.com/posts/1"
的“url”参数
如上例所示,Gin 中的可选参数也(错误地)总是在字符串开头包含斜杠。
我建议您将 URL 作为编码查询字符串传递。这会减少很多头痛。否则,我建议寻找限制较少的不同路由器或框架,因为我认为 Gin 不会很快解决这些问题 - 它们已经开放多年了。
r.GET("/users/:regex",UserHandler)
func UserHandler(c *gin.Context) {
r, err := regexp.Compile(`[a-zA-Z0-9]`)
if err != nil {
panic(err)
return
}
username := c.Param("regex")
if r.MatchString(username) == true {
c.File("index.html")
}
}