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,
	})
}
测试
相关推荐
资生算法程序员_畅想家_剑魔几秒前
Java常见技术分享-21-多线程安全-进阶模块-并发集合与线程池-ForkJoinPool
java·开发语言
Cx330❀1 分钟前
《C++ 递归、搜索与回溯》第1题:汉诺塔问题
开发语言·c++·算法·面试·回归算法
superman超哥3 分钟前
Rust Profile-Guided Optimization(PGO):数据驱动的极致性能优化
开发语言·后端·性能优化·rust·数据驱动·pgo
草莓熊Lotso6 分钟前
Qt 入门核心指南:从框架认知到环境搭建 + Qt Creator 实战
xml·开发语言·网络·c++·人工智能·qt·页面
微爱帮监所写信寄信6 分钟前
微爱帮监狱寄信邮票真伪核实接口认证方案
开发语言·python
啃火龙果的兔子8 分钟前
如何使用python开发小游戏
开发语言·python·pygame
superman超哥8 分钟前
Rust 内存对齐与缓存友好设计:性能优化的微观艺术
开发语言·后端·性能优化·rust·内存对齐·缓存优化设计·微观艺术
无言(* ̄(エ) ̄)11 分钟前
C语言--运算符/函数/结构体/指针
c语言·开发语言·数据结构·数据库·算法·mongodb
沐知全栈开发18 分钟前
PHP EOF (Heredoc)
开发语言
05大叔21 分钟前
SpringMVCDay02
java·开发语言