golang gin框架獲取參數

1.獲取URL參數

GET請求參數通過URL傳遞
URL參數可以通過DefaultQuery()Query()方法獲取
DefaultQuery()若參數不存在,返回默認值,Query()若參數不存在,返回空串

user_id := com.StrTo(ctx.Query("user_id")).MustInt64()
page := com.StrTo(ctx.DefaultQuery("page", "1")).MustInt()

2.獲取表單參數/獲取Request body參數

POST參數放在Request body中
表單傳輸爲post請求,http常見的傳輸格式爲四種:

application/json
application/x-www-form-urlencoded
application/xml
multipart/form-data

表單參數可以通過PostForm()方法獲取,該方法默認解析的是x-www-form-urlencodedfrom-data格式的參數

page := ctx.Request.PostFormValue("page")
rows := ctx.Request.PostFormValue("rows")
func (r *Request) PostFormValue(key string) string {
	if r.PostForm == nil {
		r.ParseMultipartForm(defaultMaxMemory)
	}
	if vs := r.PostForm[key]; len(vs) > 0 {
		return vs[0]
	}
	return ""
}
package controller

import (
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
)

func getRequestBody(context *gin.Context, s interface{}) error { //獲取request的body
	body, _ := context.Get("json") //轉換成json格式
	reqBody, _ := body.(string)
	decoder := json.NewDecoder(bytes.NewReader([]byte(reqBody)))
	decoder.UseNumber() //作爲數字而不是float64
	err := decoder.Decode(&s)//從body中獲取的參數存入s中
	return err
}

// 獲取post接口參數
func GetPostParams(ctx *gin.Context) (map[string]interface{}, error) {
	params := make(map[string]interface{})
	err := getRequestBody(ctx, &params)
	return params, err
}

使用場景:

//打印獲取到的參數
type UpdatePassword struct {
	UserId      int64  `json:"user_id"`
	LinkbookId  string `json:"linkbook_id"`
	OldPassword string `json:"old_password"`
	NewPassword string `json:"new_password"`
}
func UpdateUserPassword(ctx *gin.Context) {
	var updatePassword = UpdatePassword{}
    err := getRequestBody(ctx, &updatePassword)//調用了前面代碼塊中封裝的函數,自己封裝的,不是庫裏的
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(updatePassword.UserId )
	fmt.Println(updatePassword.LinkbookId )
	fmt.Println(updatePassword.OldPassword )
	fmt.Println(updatePassword.NewPassword )
}

3.獲取header參數

Header 是鍵值對,處理方便,Token一般都存header
簡單的token,session Id,cookie id等

// 通過上下文獲取header中指定key的內容
func GetHeaderByName(ctx *gin.Context, key string) string {
	return ctx.Request.Header.Get(key)
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章