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-urlencoded或from-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, ¶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 user context.bind(&user) //定义结构体 id int json:"id" name string json:"name"
总结:
如上:如果是form传值,结构体参数后面定义的是form,都可获取参数,也可绑定结构体; //如果是form传值,结构体参数后面定义的是json,都可获取参数,但绑定不了结构体;
如果是json传值,则取不了参数值,但可以绑定结构体;
获取和绑定参数如上
三种绑定方式:
context.bind() 都可以绑定
context.shouldbind() 都可以绑定
shouldbindquery() 只能绑定get
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。