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/jsonapplication/x-/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, ¶ms) 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)}补充:gin之处理form表单获取参数和映射结构体
不管是传递json还是form传值
注意 ,在结构体定义时 首字母必须大写
//定义结构体Id int form:"id"Name string form:"name"//获取和绑定参数id := context.Query(“id”)var user Usercontext.Bind(&user)//定义结构体Id int json:"id"Name string json:"name"总结:
如上:如果是form传值,结构体参数后面定义的是form,都可获取参数,也可绑定结构体; //如果是form传值,结构体参数后面定义的是json,都可获取参数,但绑定不了结构体;
如果是json传值,则取不了参数值,但可以绑定结构体;
获取和绑定参数如上
三种绑定方式:
context.Bind() 都可以绑定
context.ShouldBind() 都可以绑定
ShouldBindQuery() 只能绑定get
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。