从golang-gin-realworld-example-app项目学写httpapi (六)
https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/validators.go
验证器
package users
import (
"github.com/gin-gonic/gin"
"github.com/wangzitian0/golang-gin-starter-kit/common"
)
// 模型验证器包括2个方面: 1. 使用规则验证输入的json 2. 验证调用common.Bind(c, self)后填充的数据
// 用户验证json结构体
type UserModelValidator struct {
User struct {
Username string `form:"username" json:"username" binding:"exists,alphanum,min=4,max=255"`
Email string `form:"email" json:"email" binding:"exists,email"`
Password string `form:"password" json:"password" binding:"exists,min=8,max=255"`
Bio string `form:"bio" json:"bio" binding:"max=1024"`
Image string `form:"image" json:"image" binding:"omitempty,url"`
} `json:"user"`
userModel UserModel `json:"-"`
}
// 用户验证内置方法
func (self *UserModelValidator) Bind(c *gin.Context) error {
err := common.Bind(c, self)
if err != nil {
return err
}
// username, email, bio, password, image 必须项
self.userModel.Username = self.User.Username
self.userModel.Email = self.User.Email
self.userModel.Bio = self.User.Bio
if self.User.Password != common.NBRandomPassword {
self.userModel.setPassword(self.User.Password)
}
if self.User.Image != "" {
self.userModel.Image = &self.User.Image
}
return nil
}
// 构造函数 NewUserModelValidator, 可以配置默认值
func NewUserModelValidator() UserModelValidator {
userModelValidator := UserModelValidator{}
//userModelValidator.User.Email ="w@g.cn"
return userModelValidator
}
// 用户填充数据验证
func NewUserModelValidatorFillWith(userModel UserModel) UserModelValidator {
userModelValidator := NewUserModelValidator()
userModelValidator.User.Username = userModel.Username
userModelValidator.User.Email = userModel.Email
userModelValidator.User.Bio = userModel.Bio
userModelValidator.User.Password = common.NBRandomPassword
if userModel.Image != nil {
userModelValidator.User.Image = *userModel.Image
}
return userModelValidator
}
// 登录验证json结构体
type LoginValidator struct {
User struct {
Email string `form:"email" json:"email" binding:"exists,email"`
Password string `form:"password"json:"password" binding:"exists,min=8,max=255"`
} `json:"user"`
userModel UserModel `json:"-"`
}
// 登录验证内置方法
func (self *LoginValidator) Bind(c *gin.Context) error {
err := common.Bind(c, self)
if err != nil {
return err
}
self.userModel.Email = self.User.Email
return nil
}
// 构造函数 NewLoginValidator
func NewLoginValidator() LoginValidator {
loginValidator := LoginValidator{}
return loginValidator
}
posted on
2018-11-21 10:37
北京涛子 阅读(
...) 评论(
)
编辑
收藏
转载于:https://www.cnblogs.com/liujitao79/p/9993552.html