Gin 系列講座: Saas系統, Gin+Jwt+casbin RestFul Api 後端一戰到底 : 6 通常請求參數綁定獲取

URL查詢參數

(https://juejin.im/search?keyword=tony&type=admin&id=10 )
複製代碼

GET 請求json

func (c *Context) GetQuery(key string) (string, bool)
func (c *Context) Query(key string) string
func (c *Context) DefaultQuery(key, defaultValue string) string
func (c *Context) GetQueryArray(key string) ([]string, bool)
func (c *Context) QueryArray(key string) []string



r.GET("/user/:id", func(c *gin.Context) {
    id,_ := c.GetQuery("keyword")
    //id := c.Query("keyword")
    //id := c.DefaultQuery("keyword","tomy")   

    // http://localhost:8080/user?id=10&id=11&id=12
    //  ids := c.QueryArray("id")
})
複製代碼

請求變量在url path中

https://juejin.im/user/:id )
複製代碼

注意 GET請求: /user/:id 中的:id是變量。能夠變更的部分。 舉例子: /user/tom, /user/tony 裏面的tom, tony就是:id的不一樣的變量值。bash

那麼若是在gin中得到呢post

r.GET("/user/:id", func(c *gin.Context) {
  id, err := c.Params.Get("id")
})
複製代碼

數據綁定

type Person struct {
	Name     string    `form:"name"`
	Address  string    `form:"address"`
	Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
}

func startPage(c *gin.Context) {
	var person Person
	// If `GET`, only `Form` binding engine (`query`) used.
	// 若是是Get,那麼接收不到請求中的Post的數據??
	// 若是是Post, 首先判斷 `content-type` 的類型 `JSON` or `XML`, 而後使用對應的綁定器獲取數據.
	if c.ShouldBind(&person) == nil {
		log.Println(person.Name)
		log.Println(person.Address)
		log.Println(person.Birthday)
	}

	c.String(200, "Success")
}

複製代碼

實戰中通常用json Bind 或者 ShouldBind比較方便。 post 來獲取參數。

一下篇將介紹獲取到的參數如何驗證!

相關文章
相關標籤/搜索