Golang
Gin框架接收参数的方法
08-17 13:03在 Gin 框架中,接收 GET 和 POST 数据主要使用 Query、Param 和 ShouldBind 系列方法。以下是常见的几种接收方式:
1、GET 请求
⑴ 接收 URL 查询字符串(Query String)
//获取 phone 参数,未传参数或者传空,都将得到空字符串
phone := c.Query("phone")
fmt.Primtln(phone=="") //true,唯一判断方式,不能使用nil
//获取 phone 参数,多了个 bool 返回值,判断是否传了参数
phone, exists := c.GetQuery("phone")
if !exists {
// 参数没传
} else if mobile == "" {
// 参数传了,但是空字符串
} else {
// 有值
}
//带默认值
page := c.DefaultQuery("page", "1")
//接收所有参数并返回 map
//比如访问:比如访问“?key1=value1&key2=value2”得到的参数是:map[key1:[value1] key2:[value2]]
params := c.Request.URL.Query()
//接收并返回map格式的参数
//访问格式必须是“?params[key1]=value1¶ms[key2]=value2”接收到的参数:map[key1:value1 key2:value2]
params := c.QueryMap("params")
⑵ 接受 URL 路径参数,比如:/api/v1/id
这种方式需要先声明路由,且接收一个参数和多个参数的路由声明方式有所不同,声明路由后必须严格按照路由格式访问,否则返回404
① 声明路由
//router.go
router.GET("/api/v1/:id", handler.Aaa) //仅一个参数
router.GET("/api/v1/id/:id/title/:title", handler.Aaa) //多个参数
② 接收参数
id := c.Param("id") //对应路由中的 /:id
id := c.Param("title") //可以忽略 id 直接取 title 的值,但 URL 中不能省略 id
fmt.Println(id, title)
⑶ 接收 URL 参数并绑定到结构体
这种方式需要先定义结构体,然后使用 ShouldBindQuery 方法接收参数
//定义结构体
type Field struct {
Mobile int `form:"mobile"`
Ip string `form:"ip"`
}
func main() {
var data Field
//将 URL 参数绑定到结构体
if err := c.ShouldBindQuery(&data); err != nil {
panic(err)
}
fmt.Println(data)
}
//访问“?mobile=1383838438&ip=8.8.8.8”得到:{1383838438 8.8.8.8}
2、POST请求
⑴ 接收表单格式(form-data/x-www-form-urlencoded)
//方式一:直接获取
phone := c.PostForm("phone")
ip := c.PostForm("ip")
fmt.Println(phone, ip)
//方式二:绑定到结构体
type SendRequest struct {
Phone string `form:"phone" binding:"required,len=11"`
IP string `form:"ip" binding:"required"`
}
func main() {
var data SendRequest
err:=c.ShouldBind(&data) //将 form-data 或 x-www-form-urlencoded 绑定到结构体,参数是 form 后面引号内的字段
if err != nil {
panic(err)
}
fmt.Println(data) //打印出结构体,比如:{13838389438 8.8.8.8}
}
⑵ 接收 JSON 格式请求体(Body 为 JSON)
//定义结构体,注意其中的 tag 标签,json后面引号内的字段,对应传参时 json 的字段
type SendSmsRequest struct {
Phone string `json:"phone" binding:"required,len=11"`
IP string `json:"ip" binding:"required"`
}
func SendSms(c *gin.Context) {
var req SendSmsRequest
// 将 JSON 绑定到结构体
if err := c.ShouldBindJSON(&req); err != nil {
panic(err)
}
fmt.Println(req)
}
注意:这种方式请求时,body 直接发送 Json 即可,不用再声明 field,适合有多字段需求的情况。甚至可以在结构体内嵌套结构体,比如下面的格式:
type Admission struct {
APreliminaryScore string `json:"a_preliminary_score" gorm:"column:a_preliminary_score;type:text" binding:"required"` //要求必传
AEquivalentAbility string `json:"a_equivalent_ability" gorm:"column:a_equivalent_ability;type:varchar(255)"`
ASoldierPlan string `json:"a_soldier_plan" gorm:"column:a_soldier_plan;type:varchar(255)"`
...
}
type Examination struct {
EPreliminaryScore string `json:"e_preliminary_score" gorm:"column:e_preliminary_score;type:text" binding:"required"`
EEquivalentAbility string `json:"e_equivalent_ability" gorm:"column:e_equivalent_ability;type:varchar(255)"`
ESoldierPlan string `json:"e_soldier_plan" gorm:"column:e_soldier_plan;type:varchar(255)"`
...
}
type Other struct {
ExamZone string `json:"exam_zone" gorm:"column:exam_zone;type:text"`
Major string `json:"major" gorm:"column:major;type:text"`
...
}
//组合:HTTP请求体(接收POST参数)
type ScoreDataRequest struct {
Admission Admission `json:"admission"`
Examination Examination `json:"examination"`
Other Other `json:"other"`
}
参数传对等的二维及以上的 json,比如下面这样的参数:
{
"admission": {"a_preliminary_score":"222","a_equivalent_ability":"","a_soldier_plan":"","a_ethnic_inority_plan":"","a_policy_bonus_points":"","a_exempt_preliminary_exam":"","a_giveup_reexamination":"","a_giveup_equivalent_ability":"","a_giveup_soldier_plan":"","a_giveup_policy_bonus_points":""},
"examination": {"e_preliminary_score":"111","e_equivalent_ability":"","e_soldier_plan":"","e_ethnic_inority_plan":"","e_policy_bonus_points":"","e_exempt_preliminary_exam":"","e_giveup_reexamination":"","e_giveup_equivalent_ability":"","e_giveup_soldier_plan":"","e_giveup_policy_bonus_points":""},
"other": {"exam_zone":"A","major":"MBA","school_id":100,"user_id":10,"year":2026}
}