1. 绑定 Url 查询参数
// 定义一个 Person 结构体,用来绑定 url query
type Person struct {
Name string `form:"name"` // 使用成员变量标签定义对应的参数名
Address string `form:"address"`
}
func main() {
route := gin.Default()
route.POST("/testing", startPage)
route.Run()
}
func startPage(c *gin.Context) {
var person Person
// 将 url 查询参数和 person 绑定在一起
if c.ShouldBindQuery(&person) == nil { //说明没错误
log.Println("====== Only Bind By Query String ======")
log.Println("Name is " + person.Name)
log.Println("Address is " + person.Address)
}
c.String(200, "Success")
}
url :http://localhost:8080/testing?name=winnie&address=127.0.0.1
2. url查询参数绑定结构体
package main
import (
"github.com/gin-gonic/gin"
"log"
"time"
)
// 定义一个 Person 结构体,用来绑定数据
type Person struct {
Name string `form:"name"`
Address string `form:"address"`
Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
}
func main() {
route := gin.Default()
route.GET("/testing", startPage)
route.Run(":9999")
}
func startPage(c *gin.Context) {
var person Person
// 绑定到 person
if c.ShouldBind(&person) == nil {
log.Println(person.Name)
log.Println(person.Address)
log.Println(person.Birthday)
}
c.String(200, "Success")
}
url:
http://localhost:9999/testing?name=ocean&address=XAC&birthday=2022-09-20
3. 数据验证
Gin 的数据验证是和数据绑定结合在一起的。只需要在数据绑定的结构体成员变量的标签添加binding规则即可
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
// 定义的 Login 结构体
// 该 struct 可以绑定在 Form 和 JSON 中
// binding:"required" 意思是必要参数。如果未提供,Bind 会返回 error
type Login struct {
User string `form:"user" json:"user" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
func main() {
router := gin.Default()
// POST 到这个路由一段 JSON, 如 ({"user": "manu", "password": "123"})
router.POST("/loginJSON", func(c *gin.Context) {
var json Login
// 验证数据并绑定
if err := c.ShouldBindJSON(&json); err == nil {
if json.User == "manu" && json.Password == "123" {
c.JSON(http.StatusOK, gin.H{"status": "you are logged in",
"User": json.User,
"Password": json.Password,
})
} else {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
}
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
})
// POST 到这个路由一个 Form 表单 (user=manu&password=123)
router.POST("/loginForm", func(c *gin.Context) {
var form Login
// 验证数据并绑定
if form.User == "Winnie" && form.Password == "456" {
c.JSON(http.StatusOK, gin.H{"status": "you are logged in",
"User": form.User,
"Password": form.Password})
} else {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
}
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
})
router.Run(":8080")
}
JSON
-----------------------------------------------------------------------------------------------------------------------
form
-----------------------------------------------------------------------------------------------------------------------