1. 程式人生 > >Gin Web框架實戰速學 二 URL規則設置,帶參數的路由

Gin Web框架實戰速學 二 URL規則設置,帶參數的路由

div span 展現 路徑 輸出 我們 query 逼格 獲取

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 }

運行輸出

技術分享圖片

完了,驚不驚喜,刺不刺激

技術分享圖片

Gin Web框架實戰速學 二 URL規則設置,帶參數的路由