GoWeb开发:006.Gin数据绑定

19 阅读1分钟

绑定url 查询字符串

type User struct {
	Id      string `form:"id"`
	Name    string `form:"name"`
	Address string `form:"address"`
}
r.GET("/user/profile", func(c *gin.Context) {
	var user User
	//绑定成功
	if c.ShouldBindQuery(&user) == nil {
		c.JSON(200, gin.H{
			"user": user,
		})
		return
	}
	c.JSON(200, gin.H{
		"msg": "ok",
	})
})

示例

$ curl 'http://localhost:8080/user/profile?id=110&name=jie&address=beijing'
{"user":{"Id":"110","Name":"jie","Address":"beijing"}}

绑定Form

type LoginForm struct {
	Username string `form:"username" binding:"required"`
	Password string `form:"password" binding:"required"`
}

r.POST("/login", func(c *gin.Context) {
	var form LoginForm
	if c.ShouldBind(&form) == nil {
		if form.Username == "admin" && form.Password == "123456" {
			c.JSON(200, gin.H{"status": "you are logged in"})
		} else {
			c.JSON(401, gin.H{"status": "unauthorized"})
		}
	} else {
		c.JSON(500, gin.H{"status": "param error"})
	}
})

示例:

$ curl -X POST -d 'username=admin&password=123456' http://localhost:8080/login
{"status":"you are logged in"}

curl -X POST -d 'username=admin&password=1234567' http://localhost:8080/login
{"status":"unauthorized"}

$ curl -X POST -d 'username=admin' http://localhost:8080/login
{"status":"param error"}

绑定JSON

type RegisterForm struct {
	Username string `form:"username" binding:"required" json:"username"` //json:"username",定义json返回字段
	Password string `form:"password" binding:"required" json:"password"`
	Email    string `form:"email omitempty" json:"email"`
}
r.POST("/register", func(c *gin.Context) {
	var user RegisterForm

	if result := c.BindJSON(&user); result == nil {
		c.JSON(200, gin.H{
			"user": user,
		})
	} else {
		c.JSON(500, gin.H{"status": "param error"})
	}
})

示例:

$ curl -H "Content-Type: application/json" -X POST -d '{"username":"jie","password":"123456"}' http://localhost:8080/register
{"user":{"username":"jie","password":"123456","email":""}}

$ curl -H "Content-Type: application/json" -X POST -d '{"username":"jie","password":"123456", "email": "admin@qq.com"}' http://localhost:8080/register
{"user":{"username":"jie","password":"123456","email":"admin@qq.com"}}

$ curl -H "Content-Type: application/json" -X POST -d '{"username":"jie"}' http://localhost:8080/register
{"status":"param error"}