💜 想真正擅长编程? 从一门课程开始,100% 免费

《笔记》第三十篇 Gin接受表单数据

第30讲 Gin接受表单数据

本讲基于视频实际讲解内容整理


一、本讲概述

上一讲我们在模板里写好了表单,本讲讲解后端如何接收表单提交的数据:从最基础的 c.PostForm,到带默认值的 DefaultPostForm,再到用结构体批量绑定(ShouldBind),以及处理多值(复选框)。


二、基础取值:c.PostForm

2.1 单个字段

表单以 post 提交后,handler 用 c.PostForm("name") 按表单的 name 取值:

Go
// controller/user.go
func Login(c *gin.Context) {
    username := c.PostForm("username")
    password := c.PostForm("password")

    c.JSON(200, gin.H{
        "username": username,
        "msg":      "登录请求已收到",
    })
}
HTML
<form method="post" action="/login">
    用户名:<input name="username">
    密码:<input type="password" name="password">
    <button type="submit">登录</button>
</form>

老师强调:PostForm 的参数必须和表单 input 的 name 完全一致,大小写也要一致。取不到时返回空字符串。

2.2 带默认值:DefaultPostForm

如果字段可能为空,可以给个默认值:

Go
remember := c.DefaultPostForm("remember", "off")

三、接收多值(复选框)

同一个 name 提交多个值,用 PostFormArray:

Go
// 表单里多个 <input type="checkbox" name="hobby" value="...">
hobbies := c.PostFormArray("hobby")
// hobbies 是 []string,如 ["code", "music"]

老师说明:复选框一组用相同 name,后端用 PostFormArray 一次性拿到所有勾选值。


四、用结构体绑定(推荐)

当字段较多时,一个个 PostForm 很繁琐。可以用结构体 + 标签一次性绑定:

4.1 定义接收结构体

Go
type LoginForm struct {
    Username string `form:"username" binding:"required"`
    Password string `form:"password" binding:"required"`
}
标签 作用
form:"username" 指定对应表单字段名
binding:"required" 该字段必填,为空则绑定失败

4.2 用 ShouldBind 绑定

Go
func Login(c *gin.Context) {
    var form LoginForm
    if err := c.ShouldBind(&form); err != nil {
        c.JSON(400, gin.H{"error": err.Error()})
        return
    }

    // 绑定成功,直接用 form.Username / form.Password
    c.JSON(200, gin.H{
        "username": form.Username,
        "msg":      "登录成功",
    })
}

老师强调:ShouldBind 会根据 Content-Type 自动选择绑定方式(表单用 PostForm 绑定,JSON 用 JSON 绑定)。binding:"required" 让 Gin 帮我们做参数校验,省去手写判断。

4.3 绑定失败的处理

Go
if err := c.ShouldBind(&form); err != nil {
    c.HTML(200, "login.html", gin.H{
        "error": "用户名和密码不能为空",
    })
    return
}

实际项目中,校验失败通常返回错误提示,让用户重新填写。


五、GET 参数 vs POST 表单

取值方式 适用场景
c.PostForm 接收 post 表单
c.Query 接收 URL 查询参数 ?id=1
c.Param 接收路由参数 /post/:id
c.ShouldBind 根据 Content-Type 自动绑定

六、本讲小结

知识点 要点
c.PostForm 按 name 取单个表单值
DefaultPostForm 取不到时给默认值
PostFormArray 取复选框等多值
结构体绑定 定义带 form 标签的结构体
ShouldBind 自动按 Content-Type 绑定
binding:"required" 必填校验

七、课后练习

  1. 写 Login handler,用 c.PostForm 取 username、password 并返回 JSON
  2. 给登录表单加一个"记住我"复选框,后端用 PostFormArray 或 PostForm 接收
  3. 定义 LoginForm 结构体,用 ShouldBind 绑定并加 binding:"required"
  4. 当 ShouldBind 失败时,返回 400 和错误信息
  5. 写"发布帖子"表单(标题、内容),用结构体绑定接收
  6. 对比 c.PostForm 与 c.Query 的区别,分别写示例