模型绑定和校
模型绑定的作用是将请求体绑定到自定义类型,目前Gin支持:JSON、XML、YAML和标准form请求参数(比如:foo=bar&boo=baz)。Gin使用go-payground/validator/validtor/v10,做参数的校验。若参数是必输,可以说明的使用binding:"required"修饰之。当在绑定的时候发现是空值就会返回错误。所以语法格式:
绑定标签类型:"fieldname" binding:"required"
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
gorm.Model
Name string `form:"name" json:"name" xml:"name" binding:"required"`
Mark int `form:"mark" json:"mark" xml:"mark" binding:"required"`
}
func (User) TableName() string {
return "users"
}
var db *gorm.DB
func init() {
dsn := "root:123456@tcp(127.0.0.1)/test?charset=utf8mb4&parseTime=True&loc=Local"
d, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println("open mysql failed,", err)
}
db = d
db.AutoMigrate(&User{})
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(500)
sqlDB.SetConnMaxLifetime(time.Hour)
}
func postApi(c *gin.Context) {
var form User
if err := c.ShouldBind(&form); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if error := db.Create(&form).Error; error != nil {
fmt.Println("插入失败", error)
return
}
c.JSON(http.StatusOK, gin.H{"data": &form})
}
func main() {
r := gin.Default()
r.POST("addInfo", postApi)
r.Run()
}
绑定Url
示例代码
此类型主要用在RESTful类型的接口,具体的示例代码如下:
package main
import "github.com/gin-gonic/gin"
func main() {
route := gin.Default()
route.GET("/:name/:id", func (c *gin.Context) {
c.JSON(200, gin.H{
"name": c.Param("name"),
"uuid": c.Param("id"),
})
})
route.Run()
}