(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. 💕👉博客专栏

相关推荐
源代码•宸15 小时前
GoLang八股(Go语言基础)
开发语言·后端·golang·map·defer·recover·panic
iso少年17 小时前
Go 语言并发编程核心与用法
开发语言·后端·golang
风送雨1 天前
Go 语言进阶学习:第 2 周 —— 接口、反射与错误处理进阶
开发语言·学习·golang
峰上踏雪1 天前
Go(Golang)Windows 环境配置关键点总结
开发语言·windows·golang·go语言
我不是8神1 天前
go语言语法基础全面总结
开发语言·golang·xcode
qq_172805591 天前
Modbus Server 模拟平台之RTU协议
golang·modbus
源代码•宸1 天前
Leetcode—1339. 分裂二叉树的最大乘积【中等】
开发语言·后端·算法·leetcode·golang·dfs
源代码•宸1 天前
Leetcode—166. 加一【简单】new(big.Int)法
经验分享·算法·leetcode·职场和发展·golang·new.bigint
源代码•宸1 天前
GoLang基础语法(go语言结构、go语言变量、go语言常量、go语言运算符)
开发语言·后端·golang
ghostwritten1 天前
go.mod 与go.sum有什么区别?
开发语言·后端·golang