gin的路由使用的是httprouter库(请自行github一下),性能好,相对功可以用git
传统的一些API路径设计方式(仔细看看行不行)github
GET /topic/{topic_id} 获取帖子明细
GET /topic/{user_name} 获取用户发布的帖子列表
GET /topic/top 获取最热帖子列表api
咱们上节课的代码改正下restful
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的帖子“”spa
上述代码的局限 目前不支持正则,也不支持 固定路径和参数路径共存 譬如 router.GET("/topic/:id", xxxoo) router.GET("/topic/user", xxxoo) 甚至 "/topic/user/:username" 也会冲突
因此须要从新设计API规则,咱们设置下面一些有逼格的设计
须要知足3点(姓什么,名什么,家住哪里)rest
1、api有版本信息 譬如 /v1/xxxoo /v2/xxxoo 二、尽量使用复数,且含义明确。名词最佳 /v1/topics /v1/users /v1/getusers //不推荐 3、 使用GET参数规划数据展示规则 /v1/users //显示所有或默认条数 /v1/users?limit=10 //只显示10条 /v1/topics?username=xxxoo //显示xxoo的帖子
v1表明版本号,后面改版可能为v2
其实就是restful Api的规则啦,所以刚才那两个货咱们改为这样code
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 }
运行输出router
完了,惊不惊喜,刺不刺激