ShouldBind、ShouldBindJson、ShouldBindQuery的区别

|---------------------|-----------|---------------------|----------|
| 方法 | 数据来源 | Content-Type 要求 | 自动检测 |
| ShouldBind() | 自动检测 | 不限 | 是 |
| ShouldBindJSON() | 只读 JSON | application/json | 否 |
| ShouldBindQuery() | 只读 URL 参数 | 无 | 否 |

Content-Type 决定解析方式:

Content-Type 解析方式
application/json JSON 解析
multipart/form-data 表单解析
application/x-www-form-urlencoded 表单解析

常见的 Content-Type

Content-Type 含义 数据长什么样
application/json JSON 格式 {"name": "张三", "age": 18}
text/html HTML 网页 <html><body>...</body></html>
text/plain 纯文本 这是一段文字
multipart/form-data 表单+文件 表单字段
image/jpeg JPEG 图片 图片二进制数据

shouldbind:

特点:自动检测 Content-Type;支持多种数据格式;根据请求类型选择绑定方式

支持的content-type:

(1)application/json → JSON 绑定

(2)application/xml → XML 绑定

(3)multipart/form-data → 表单绑定(含文件)

(4)application/x-www-form-urlencoded → 表单绑定

Go 复制代码
func CreateUser(c *gin.Context) {
    var req UserRequest
    // 自动识别 Content-Type
    if err := c.ShouldBind(&req); err != nil {
        c.JSON(400, gin.H{"error": err.Error()})
        return
    }
    // 处理业务
}

shouldbindjson--专为JSON

Go 复制代码
func (c *Context) ShouldBindJSON(obj interface{}) error

特点:只处理JSON格式;要求 Content-Type: application/json;性能稍好(省去类型判断)

示例:

Go 复制代码
func CreateUser(c *gin.Context) {
    var req UserRequest
    // 明确要求 JSON 格式
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(400, gin.H{"error": "请提供正确的JSON格式"})
        return
    }
    // 处理业务
}

shouldbindquery:

Go 复制代码
func (c *Context) ShouldBindQuery(obj interface{}) error

特点:只绑定URL查询参数(?key=value);忽略请求体;适用于GET请求

示例:

Go 复制代码
// GET /api/users?page=1&page_size=10&name=john
func GetUsers(c *gin.Context) {
    var query UserQuery
    // 只绑定查询参数
    if err := c.ShouldBindQuery(&query); err != nil {
        c.JSON(400, gin.H{"error": err.Error()})
        return
    }
    fmt.Println(query.Page)     // 1
    fmt.Println(query.PageSize) // 10
    fmt.Println(query.Name)     // "john"
}

结构体标签详解

json--JSON字段映射--json:"user_name"

form--表单字段映射--form:"user_name"

uri--路径参数映射--uri:"id"

header--HTTP头部映射--header:"X-Token"

xml--XML字段映射--xml:"user_name"

yaml--YAML字段映射--yaml:"user_name"

相关推荐
高频因子挖掘机1 小时前
回测收益为什么可能不真实?从时间戳、数据可用性到未来函数检查
后端·github·api
行百里er10 小时前
Redis 完结篇——Redis 热点问题在 Spring Boot 项目中实战
redis·后端
高频因子挖掘机11 小时前
只取最近 60 个交易日,却每次拉全历史:量化脚本变慢的原因与改法
后端·github·api
孟健11 小时前
从5000亿Token到83%字节匹配:AI逆向工程与重构的工程闭环实践
后端·架构·ai编程
码事漫谈12 小时前
丢得静悄悄,谈一谈 Agent 的记忆是怎么没的
后端
迪飞特科技12 小时前
智慧物业平台实战:Spring Boot 整合小程序实现报修巡检费用全流程
spring boot·后端·小程序
考虑考虑12 小时前
@JsonInclude注解使用
spring boot·后端·spring
IT_陈寒13 小时前
Vite的这个问题坑了我三天,原来如此解决!
前端·人工智能·后端
网易云信13 小时前
大模型能上岗做销售吗?我们让 12 款国产模型交了 420 份作业
前端·后端
CCblandy13 小时前
HTTP 长连接 3 类故障实测:[WinError 10053]、99 个 TIME_WAIT、69 次多余握手,4 种对策怎么选
后端·python·网络协议·http·云原生·性能优化·架构