validator检验

package validator

import (
	"fmt"
	"reflect"
)


func isStructPtr(t reflect.Type) bool {
	return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
}

func isNilOrZero(v reflect.Value) bool {
	switch v.Kind() {
	default:
		return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface())
	case reflect.Interface, reflect.Ptr:
		return v.IsNil()
	}
}

func CheckRequired(obj interface{}, fields ...string) error  {
	reflectType := reflect.TypeOf(obj)
	reflectValue := reflect.ValueOf(obj)
	if !isStructPtr(reflectType) {
		return fmt.Errorf(
			"expected unnamed object value to be a pointer to a struct but got type %s "+
				"with value %v",
			reflectType,
			obj,
		)
	}
	elem := reflectValue.Elem()
	for i := 0; i < len(fields); i++ {
		name := fields[i]
		val := elem.FieldByName(name)
		if isNilOrZero(val) {
			return fmt.Errorf("the field of [ %s ] can't be empty", name)
		}
	}
	return nil
}