restful路由
gin的路由来自httprouter库。因此httprouter具有的功能,gin也具有,不过gin不支持路由正则表达式:
func
main
(){
router
:= gin.
Default
()
router.
GET
(
"/user/:name"
, func(c *gin.Context) {
name := c.
Param
(
"name"
)
c.
String
(http.StatusOK,
"Hello %s"
, name)
})
}
冒号:加上一个参数名组成路由参数。可以使用c.Params的方法读取其值。当然这个值是字串string。诸如/user/rsj217,和/user/hello都可以匹配,而/user/和/user/rsj217/不会被匹配。
☁ ~ curl http:
//127.0.0.1:8000/user/rsj217
Hello rsj217% ☁ ~ curl http:
//127.0.0.1:8000/user/rsj217/
404
page
not
found% ☁ ~ curl http:
//127.0.0.1:8000/user/
404
page
not
found%
除了:,gin还提供了*号处理参数,*号能匹配的规则就更多。
func
main
(){
router
:= gin.
Default
()
router.
GET
(
"/user/:name/*action"
, func(c *gin.Context) {
name := c.
Param
(
"name"
)
action := c.
Param
(
"action"
)
message := name +
" is "
+ action
c.
String
(http.StatusOK, message)
})
}
访问效果如下
☁ ~ curl
http:
/
/127.0.0.1:8000/user
/rsj217/
rsj217 is /% ☁ ~ curl
http:
/
/127.0.0.1:8000/user
/rsj217/
中国
rsj217 is /中国%