gin的路由使用的是httprouter库(请自行github一下),性能好,相对功能够用
传统的一些API路径设计方式(仔细看看行不行)
GET /topic/{topic_id} 获取帖子明细
GET /topic/{user_name} 获取用户发布的帖子列表
GET /topic/top 获取最热帖子列表
我们上节课的代码改正下
package main import "github.com/gin-gonic/gin" func main() { router := gin.Default() router.GET("/topic/:topic_id", func(c *gin.Context) { c.String(200,"获取topicid=%s的帖子",c.Param("topic_id")) }) router.Run() // listen and serve on 0.0.0.0:8080 }
访问 http://localhost:8080/topic/123 地址
可以输出 “”获取topicid=123的帖子“”
上述代码的局限 目前不支持正则,也不支持 固定路径和参数路径共存 譬如 router.GET("/topic/:id", xxxoo) router.GET("/topic/user", xxxoo) 甚至 "/topic/user/:username" 也会冲突
所以需要重新设计API规则,我们设置下面一些有逼格的
需要满足3点(姓什么,名什么,家住哪里)
1、api有版本信息 譬如 /v1/xxxoo /v2/xxxoo 2、尽可能使用复数,且含义明确。名词最佳 /v1/topics /v1/users /v1/getusers //不推荐 3、 使用GET参数规划数据展现规则 /v1/users //显示全部或默认条数 /v1/users?limit=10 //只显示10条 /v1/topics?username=xxxoo //显示xxoo的帖子
v1代表版本号,后面改版可能为v2
其实就是restful Api的规则啦,因此刚才那两个货我们改成这样
package main import "github.com/gin-gonic/gin" func main() { router := gin.Default() router.GET("/v1/topics", func(c *gin.Context) {
//加个if else判断而已 if c.Query("username")==""{ //Query是获取问号?后面的参数值 c.String(200,"获取帖子列表") }else { c.String(200,"获取用户=%s的帖子列表",c.Query("username")) } })
//劳资还是天下第一 router.GET("/v1/topics/:topic_id", func(c *gin.Context) { c.String(200,"获取topicid=%s的帖子",c.Param("topic_id")) //Param是获取路由的预留值 }) router.Run() // listen and serve on 0.0.0.0:8080 }
运行输出
完了,惊不惊喜,刺不刺激