golang gin——controller 模型绑定与参数校验

controller 模型绑定与参数校验

gin框架提供了多种方法可以将请求体的内容绑定到对应struct上,并且提供了一些预置的参数校验

绑定方法

根据数据源和类型的不同,gin提供了不同的绑定方法

  • Bind, shouldBind: 从form表单中去绑定对象
  • BindJSON, shouldBindJSON: 这两个方法是从json表单中去绑定对象
  • 还有从xml,protobuf等等
参数校验

gin提供了一系列预置的参数校验,可以参考官方文档。 用binding 标签

  • required 必须参数

  • number 要求数字

  • omitempty 允许为空

  • email 邮件格式

等等

实例
go 复制代码
package course

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

func InitRouters(r *gin.Engine) {
	//使用路由分组
	api := r.Group("api")
	initCourse(api)
}

func initCourse(group *gin.RouterGroup) {
	// 路由分组
	v1 := group.Group("/v1")
	{
		// /api/v1/course
		// 路径携带参数
		v1.GET("/course/search/:id", course.Get)
		v1.POST("/course/add/:id", course.Add)
		v1.PUT("/course/edit/:id", course.Edit)
		v1.DELETE("/course/del", course.Delete)
	}
}

// 模型绑定, gin 引用了 validator,有一些预置标签
type course struct {
	Name string 		`json:"name"     form:"name" binding:"required"`
	Teacher string		`json:"teacher"  form:"teacher" binding:"required"`
	Duration int		`json:"duration" form:"duration" binding:"number"`
}

func Add(c *gin.Context) {
	req := &course{}


	// 从form表单去绑定 c.Bind() c.ShouldBind()
	// 从json里去取值 c.BindJSON()
	// 带should的bind 可以去返回错误,不带的会直接响应请求

	err := c.ShouldBindJSON(req)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, req)
}

func Get(c *gin.Context) {
	// 获取路径上的参数
	id := c.Param("id")

	// 都是gin.context作为入参
	c.JSON(http.StatusOK, gin.H{
		"method": c.Request.Method,
		"path": c.Request.URL.Path,
		"id": id,
	})
}

func Edit(c *gin.Context) {
	req := &course{}
	err := c.ShouldBindJSON(req)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"method": c.Request.Method,
		"path": c.Request.URL.Path,
		"req": req,
	})
}

func Delete(c *gin.Context) {
	// 从queryString 获取
	id := c.Query("id")
	// 都是gin.context作为入参
	c.JSON(http.StatusOK, gin.H{
		"method": c.Request.Method,
		"path": c.Request.URL.Path,
		"id": id,
	})
}
测试
相关推荐
七七&5564 小时前
2024年08月13日 Go生态洞察:Go 1.23 发布与全面深度解读
开发语言·网络·golang
java坤坤4 小时前
GoLand 项目从 0 到 1:第八天 ——GORM 命名策略陷阱与 Go 项目启动慢问题攻坚
开发语言·后端·golang
元清加油4 小时前
【Golang】:函数和包
服务器·开发语言·网络·后端·网络协议·golang
健康平安的活着4 小时前
java之 junit4单元测试Mockito的使用
java·开发语言·单元测试
DjangoJason6 小时前
C++ 仿RabbitMQ实现消息队列项目
开发语言·c++·rabbitmq
m0_480502646 小时前
Rust 入门 KV存储HashMap (十七)
java·开发语言·rust
大阳1236 小时前
线程(基本概念和相关命令)
开发语言·数据结构·经验分享·算法·线程·学习经验
YA3336 小时前
java基础(九)sql基础及索引
java·开发语言·sql
恋喵大鲤鱼6 小时前
Golang 后台技术面试套题 1
面试·golang
奇树谦7 小时前
QT|windwos桌面端应用程序开发,当连接多个显示器的时候,如何获取屏幕编号?
开发语言·qt