common.go 736 字节
package utils

import (
	"fmt"
	"github.com/beego/beego/v2/core/validation"
	"reflect"
	"strings"
)

// ValidateCommand 验证输入参数
func ValidateCommand(commandType interface{}) error {
	valid := validation.Validation{}
	b, err := valid.Valid(commandType)
	if err != nil {
		return err
	}
	if !b {
		elem := reflect.TypeOf(commandType).Elem()
		for _, validErr := range valid.Errors {
			field, isExist := elem.FieldByName(validErr.Field)
			if isExist {
				if tag := field.Tag.Get("cname"); len(tag) > 0 {
					return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, tag, -1))
				} else {
					return fmt.Errorf(validErr.Message)
				}
			} else {
				return fmt.Errorf(validErr.Message)
			}
		}
	}
	return nil
}