Gin 参数绑定

144 阅读1分钟
  1. 解析错误会在header中写一个400的状态码
//内部根据Content-Type去解析
c.Bind(obj interface{})
//内部替你传递了一个binding.JSON,对象去解析
c.BindJSON(obj interface{})
//解析哪一种绑定的类型,根据你的选择,binding.Form 表单
c.BindWith(obj interface{}, b binding.Binding)
  1. 解析错误直接返回,至于要给客户端返回什么错误状态码由你决定
//内部根据Content-Type去解析
c.ShouldBind(obj interface{})
//内部替你传递了一个binding.JSON,对象去解析
c.ShouldBindJSON(obj interface{})
//解析哪一种绑定的类型,根据你的选择,binding.Form 表单
c.ShouldBindWith(obj interface{}, b binding.Binding)
  1. 区别:
  • Shouldxxx:解析错误直接返回,返回什么错误状态码由自己决定。

  • bindxxx:解析错误会在header中写一个400的状态码

  1. 部分函数的示例:
package main

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

type LoginForm struct {
	User     string `form:"user" binding:"required"`
	Password string `form:"password" binding:"required"`
        Age      int    `form:"age" json:"age"`
}

func main() {
	router := gin.Default()
	router.POST("/login", func(c *gin.Context) {
		// 你可以使用显式绑定声明绑定 multipart form:
		// c.ShouldBindWith(&form, binding.Form)
		// 或者简单地使用 ShouldBind 方法自动绑定:
		var form LoginForm
		// 在这种情况下,将自动选择合适的绑定
		if c.ShouldBind(&form) == nil {
			c.JSON(http.StatusOK, gin.H{ 
                        "user": form.User, 
                        "passwd": form.Password, 
                        "age": form.Age, })
		}
	})
	router.Run(":8080")
}

结构体中,设置了binding标签的字段(userpasswd),如果没传会抛错误。非banding的字段(age),对于客户端没有传,LoginForm结构会用零值填充。对于LoginForm结构没有的参数,会自动被忽略。

好文推荐:

Multipart/Urlencoded 绑定

参数绑定