github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/znet/value.go (about)

     1  package znet
     2  
     3  import (
     4  	"errors"
     5  	"reflect"
     6  
     7  	"github.com/sohaha/zlsgo/zreflect"
     8  	"github.com/sohaha/zlsgo/zvalid"
     9  )
    10  
    11  // Content-Type MIME of the most common data formats
    12  const (
    13  	mimeJSON              = "application/json"
    14  	mimePlain             = "text/plain"
    15  	mimePOSTForm          = "application/x-www-form-urlencoded"
    16  	mimeMultipartPOSTForm = "multipart/form-data"
    17  )
    18  
    19  func (c *Context) valid(obj interface{}, v map[string]zvalid.Engine) error {
    20  	r := make([]*zvalid.ValidEle, 0, len(v))
    21  	val := zreflect.ValueOf(obj)
    22  	if val.Kind() != reflect.Ptr {
    23  		return errors.New("result must be a pointer")
    24  	}
    25  
    26  	val = val.Elem()
    27  	typ := zreflect.TypeOf(val)
    28  	for i := 0; i < typ.NumField(); i++ {
    29  		field := val.Field(i)
    30  		name, _ := zreflect.GetStructTag(typ.Field(i))
    31  		switch field.Kind() {
    32  		case reflect.String, reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
    33  			value := field.Interface()
    34  			if rv, ok := v[name]; ok {
    35  				r = append(r, zvalid.BatchVar(field, rv.VerifiAny(value)))
    36  			}
    37  		case reflect.Struct:
    38  		case reflect.Slice:
    39  		default:
    40  			return errors.New("value validation for " + name + " is not supported")
    41  		}
    42  	}
    43  
    44  	return zvalid.Batch(r...)
    45  }
    46  
    47  func (c *Context) BindValid(obj interface{}, v map[string]zvalid.Engine) error {
    48  	err := c.Bind(obj)
    49  	if err != nil {
    50  		return err
    51  	}
    52  
    53  	return c.valid(obj, v)
    54  }