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,
	})
}
测试
相关推荐
CodeCraft Studio22 分钟前
PDF处理控件Aspose.PDF教程:使用 Python 将 PDF 转换为 Base64
开发语言·python·pdf·base64·aspose·aspose.pdf
零点零一23 分钟前
VS+QT的编程开发工作:关于QT VS tools的使用 qt的官方帮助
开发语言·qt
lingchen19063 小时前
MATLAB的数值计算(三)曲线拟合与插值
开发语言·matlab
gb42152873 小时前
java中将租户ID包装为JSQLParser的StringValue表达式对象,JSQLParser指的是?
java·开发语言·python
一朵梨花压海棠go3 小时前
html+js实现表格本地筛选
开发语言·javascript·html·ecmascript
蒋星熠3 小时前
Flutter跨平台工程实践与原理透视:从渲染引擎到高质产物
开发语言·python·算法·flutter·设计模式·性能优化·硬件工程
翻滚丷大头鱼4 小时前
Java 集合Collection—List
java·开发语言
aramae4 小时前
C++ -- 模板
开发语言·c++·笔记·其他
胡耀超4 小时前
4、Python面向对象编程与模块化设计
开发语言·python·ai·大模型·conda·anaconda
索迪迈科技4 小时前
java后端工程师进修ing(研一版 || day40)
java·开发语言·学习·算法