(Go Gin)Gin学习笔记(三)数据解析和绑定:结构体分析,包括JSON解析、form解析、URL解析,区分绑定的Bind方法

1. 数据解析和绑定

bind或bindXXX函数(后文中我们统一都叫bind函数)的作用就是将请求体中的参数值绑定到对应的结构体上,以方便后续业务逻辑的处理

1.1 JSON数据解析和绑定

  • 客户端传参,后端接收并解析到结构体
go 复制代码
package main

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

///

type Login struct {
	Username string `form:"username" json:"username" binding:"required" msg:"用户名不能为空"`
	Password string `form:"password" json:"password" binding:"required"`
}

///

func demo(res *gin.Context) {
	var json Login

	// ShouldBind() msg:"用户名不能为空"将request的body中的数据,自动按照json格式解析到结构体
	if err := res.ShouldBind(&json); err != nil {
		res.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	log.Println("user:", json.Username, "\n", "password:", json.Password)

	res.JSON(http.StatusOK, gin.H{})
}

func main() {
	r := gin.Default()

	r.POST("/demo", demo)
	r.Run(":8080")
}

1.1.1 结构体分析

Password 使用了 binding:"required"

标签中,binding标签为其属性设置了必填项

  • 如果字符串为空:"",ShouldBind,一样会报400错
  • 如果使用 binding:"-", 就不会进行必填项检验了

1.2 form数据解析和绑定

go 复制代码
package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

///

type Login struct {
	Username string `form:"username" json:"测试" binding:"required" msg:"用户名不能为空"`
	Password string `form:"password" binding:"required"`
}

///

func demo(res *gin.Context) {
	var json Login

	// Bind() 默认解析并绑定form格式
	// 根据请求头中content-type自动推断
	if err := res.Bind(&json); err != nil {
		res.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	//log.Println("user:", json.Username, "\n", "password:", json.Password)
	res.JSON(http.StatusOK, gin.H{
		"user": json.Username,
		"pass": json.Password,
	})
}

func main() {
	r := gin.Default()

	r.POST("/demo", demo)
	r.Run(":8080")
}

1.3 URI数据解析和绑定

go 复制代码
package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

///

type Login struct {
	Username string `form:"username" json:"测试" binding:"required" msg:"用户名不能为空"`
	Password string `form:"password" binding:"required"`
}

///

func demo(res *gin.Context) {
	var json Login

	// Bind() 默认解析并绑定form格式
	// 根据请求头中content-type自动推断
	if err := res.ShouldBindUri(&json); err != nil {
		res.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	//log.Println("user:", json.Username, "\n", "password:", json.Password)
	res.JSON(http.StatusOK, gin.H{
		"user": json.Username,
		"pass": json.Password,
	})
}

func main() {
	r := gin.Default()

	r.POST("/demo", demo)
	r.Run(":8080")
}

1.4 绑定的方法区别

gin 为数据解析进行了多方面的设置,

面对不同的前端数据有统一的代码处理方法。其本质上,还是将表单数据中每个数据的key值与结构中的数据一一对应。

  • ShouldBindJSON()
  • ShouldBindXML()
  • ShouldBind()
  • ...

翻阅context的源码,就能看到Bind和ShouldBind这两类方法

ShouldBind() Bind()
只会返回错误信息,不会往header里面写400的错误状态码 返回错误,并在header里面写400的状态码

这是两者最大的差异,是否会在header中添加400的错误状态码

2. ❤️GoGin框架------前文链接

Gin框架学习参考网站:gin框架·Go语言中文文档

3. 💕👉博客专栏

相关推荐
张忠琳21 小时前
【Go 1.26.4】Golang Slice 深度解析
开发语言·后端·golang
张忠琳1 天前
【Go 1.26.4】Golang Channel 深度解析
开发语言·后端·golang
张忠琳2 天前
【Go 1.26.4】Golang Map 深度解析
开发语言·后端·golang
何以解忧,唯有..2 天前
Go 语言安装与环境配置完整指南
开发语言·后端·golang
踏着七彩祥云的小丑2 天前
Go 学习第6天:结构体 + 切片 + range遍历
开发语言·学习·golang·go
浮尘笔记2 天前
Go实现大文件异步流式采集引擎
开发语言·后端·golang
l齐天2 天前
Ubuntu 中编译 Go + PBC 程序为 Windows 11 可运行文件
windows·ubuntu·golang
jieyucx2 天前
《Go 数据库编程开篇:彻底打通 database/sql 与 MySQL 驱动的连接池调优密码》
数据库·sql·golang
壮Sir不壮2 天前
GO语言——GMP调度模型
linux·开发语言·golang·go·操作系统·线程·协程
再玩一会儿看代码2 天前
2026 年 ChatGPT 套餐怎么选?Free、Go、Plus、Pro、Business、Enterprise 一次讲清楚
人工智能·gpt·chatgpt·golang·openai·codex