Files
easygoadmin-wiki/EasyGoAdmin_Gin_AntdVue/zh/api-spec/binding.md
T
2026-10-25 17:24:27 +08:00

64 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 8.4 请求绑定与参数校验
:::tip 概述
请求绑定由反射路由层统一完成:写入顺序 query → body → path(后写覆盖),校验读 binding 标签、错误消息取 msg 标签。文件类请求经 UnmarshalBody 逃生舱接管。
:::
## 绑定优先级
```text
写入顺序:query(GET 参数)→ body(JSON)→ path(路径参数)
最终优先级:path > body > query
```
字段带 `json`(body)与 `form`(query)双标签即可参与两种来源;路径参数(`:id`)按名覆盖同名字段。
## 校验标签
```go
// internal/model/dto/user.go(真实契约)
Username string `json:"username" binding:"required,min=2,max=30" msg:"请输入用户名;用户名长度需在2~30位"`
Mobile string `json:"mobile" binding:"omitempty,phone" msg:"手机号格式不正确"`
```
| 标签 | 作用 |
|---|---|
| binding | 规则(required/min/max/oneof/gte/lte/omitempty/phone/email…) |
| msg | 失败提示语(直接作为信封 msg);`;` 分段与多规则一一对应,单段适用全部规则 |
| dc | 字段说明(OpenAPI 文档生成) |
校验在 handler 前完成,**快速失败**(返回第一条错误);内嵌 PageReq 递归校验。失败即信封返回,业务代码零参与。
## 各类载荷示例
| 载荷 | 方式 |
|---|---|
| GET 查询参数 | form 标签 + query |
| JSON body | json 标签 |
| 路径参数 | path 模板 `:id` + 同名字段 |
| multipart 文件 | UnmarshalBody 逃生舱 |
| 批量删除 | `Ids []int64` + `min=1` |
## UnmarshalBody 逃生舱
结构体实现以下接口即接管解析(文件上传标准姿势):
```go
type BodyUnmarshaler interface {
UnmarshalBody(c *gin.Context) error
}
```
返回 error = 校验失败,同样走统一信封。
## 接口调试要点
- 分页参数走 query:`?pageNo=1&pageSize=10`
- 修改类(PUT)建议全量提交业务字段(Update 全量表单语义)
- 路径参数与 body 同名冲突时以路径为准
## 相关
- [3.8 参数校验与错误上抛](/zh/guide/validation.html)(开发视角)
- [3.3 契约层开发(dto)](/zh/guide/dto.html)