go中的验证包-validator
程序员文章站
2022-07-12 11:29:37
...
https://studygolang.com/articles/29740?fr=sidebar
go get github.com/go-playground/validator/v10
package controller
import (
"fmt"
"github.com/gofiber/fiber"
uuid "github.com/satori/go.uuid"
"git.shining3d.com/cloud3d/gdocserver/common"
)
/*!
* 添加数据到cate
*/
func AddCate(c *fiber.Ctx) {
type AddParams struct {
IsDeleted string `json:"isDeleted" validate:"omitempty,oneof=n y"`
Name string `json:"name" validate:"required,max=255"`
CateType string `json:"cateType" validate:"required,oneof=group tag project"`
ParentId string `json:"parentId" validate:"omitempty,uuid"`
}
var cs = &AddParams{}
/// 解析参数到结构体
if err := c.QueryParser(cs); err != nil {
common.Log.Error().AnErr("err", err).Msg("controller:AddCate")
c.JSON(fiber.Map{
"status": false,
"msg": fmt.Sprintf("%s", err),
})
return
}
err := common.Validate.Struct(cs) // 验证结构体参数 // common.Validate =validator.New()
if err != nil {
for _, err := range err.(validator.ValidationErrors) {
fmt.Printf("%T=%v\n", err, err)
}
}
c.JSON(fiber.Map{
"status": false,
"msg": fmt.Sprintf("%s", err),
})
return
uid := uuid.NewV4().String() // 生成UUID
}
上一篇: postman 官方 test 脚本样例