從golang-gin-realworld-example-app項目學寫httpapi (六)

https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/validators.gogit

驗證器

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
}
相關文章
相關標籤/搜索