yinl_li 发表于 2018-9-20 11:55:27

golang 如何验证struct字段的数据格式

package main  import (
  "fmt"
  "reflect"
  "regexp"
  "strings"
  )
  const tagName = "validate"
  //邮箱验证正则
  var mailRe = regexp.MustCompile(`\A[\w+\-.]+@+(\.+)*\.+\z`)
  //验证接口
  type Validator interface {
  Validate(interface{}) (bool, error)
  }
  type DefaultValidator struct {
  }
  func (v DefaultValidator) Validate(val interface{}) (bool, error) {
  return true, nil
  }
  type StringValidator struct {
  Min int
  Max int
  }
  func (v StringValidator) Validate(val interface{}) (bool, error) {
  l := len(val.(string))
  if l == 0 {
  return false, fmt.Errorf("cannot be blank")
  }
  if l < v.Min {
  return false, fmt.Errorf(&quot;should be at least %v chars long&quot;, v.Min)
  }
  if v.Max >= v.Min && l > v.Max {
  return false, fmt.Errorf(&quot;should be less than %v chars long&quot;, v.Max)
  }
  return true, nil
  }
  type NumberValidator struct {
  Min int
  Max int
  }
  func (v NumberValidator) Validate(val interface{}) (bool, error) {
  num := val.(int)
  if num < v.Min {
  return false, fmt.Errorf(&quot;should be greater than %v&quot;, v.Min)
  }
  if v.Max >= v.Min && num > v.Max {
  return false, fmt.Errorf(&quot;should be less than %v&quot;, v.Max)
  }
  return true, nil
  }
  type EmailValidator struct {
  }
  func (v EmailValidator) Validate(val interface{}) (bool, error) {
  if !mailRe.MatchString(val.(string)) {
  return false, fmt.Errorf(&quot;is not a valid email address&quot;)
  }
  return true, nil
  }
  func getValidatorFromTag(tag string) Validator {
  args := strings.Split(tag, &quot;,&quot;)
  switch args {
  case &quot;number&quot;:
  validator := NumberValidator{}
  //将structTag中的min和max解析到结构体中
  fmt.Sscanf(strings.Join(args, &quot;,&quot;), &quot;min=%d,max=%d&quot;, &validator.Min, &validator.Max)
  return validator
  case &quot;string&quot;:
  validator := StringValidator{}
  fmt.Sscanf(strings.Join(args, &quot;,&quot;), &quot;min=%d,max=%d&quot;, &validator.Min, &validator.Max)
  return validator
  case &quot;email&quot;:
  return EmailValidator{}
  }
  return DefaultValidator{}
  }
  func validateStruct(s interface{}) []error {
  errs := []error{}
  v := reflect.ValueOf(s)
  for i := 0; i < v.NumField(); i++ {
  //利用反射获取structTag
  tag := v.Type().Field(i).Tag.Get(tagName)
  if tag == &quot;&quot; || tag == &quot;-&quot; {
  continue
  }
  validator := getValidatorFromTag(tag)
  valid, err := validator.Validate(v.Field(i).Interface())
  if !valid && err != nil {
  errs = append(errs, fmt.Errorf(&quot;%s %s&quot;, v.Type().Field(i).Name, err.Error()))
  }
  }
  return errs
  }
  type User struct {
  Id    int    `validate:&quot;number,min=1,max=1000&quot;`
  Namestring `validate:&quot;string,min=2,max=10&quot;`
  Bio   string `validate:&quot;string&quot;`
  Email string `validate:&quot;email&quot;`
  }
  func main() {
  user := User{
  Id:    0,
  Name:&quot;superlongstring&quot;,
  Bio:   &quot;&quot;,
  Email: &quot;foobar&quot;,
  }
  fmt.Println(&quot;Errors:&quot;)
  for i, err := range validateStruct(user) {
  fmt.Printf(&quot;\t%d. %s\n&quot;, i+1, err.Error())
  }
  }

页: [1]
查看完整版本: golang 如何验证struct字段的数据格式