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

     1  package znet
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/sohaha/zlsgo/zjson"
     7  	"github.com/sohaha/zlsgo/zreflect"
     8  	"github.com/sohaha/zlsgo/ztype"
     9  )
    10  
    11  func (c *Context) Bind(obj interface{}) (err error) {
    12  	method := c.Request.Method
    13  	if method == "GET" {
    14  		return c.BindQuery(obj)
    15  	}
    16  	contentType := c.ContentType()
    17  	if contentType == c.ContentType(ContentTypeJSON) {
    18  		return c.BindJSON(obj)
    19  	}
    20  	return c.BindForm(obj)
    21  }
    22  
    23  func (c *Context) BindJSON(obj interface{}) error {
    24  	body, err := c.GetDataRaw()
    25  	if err != nil {
    26  		return err
    27  	}
    28  	return zjson.Unmarshal(body, obj)
    29  }
    30  
    31  func (c *Context) BindQuery(obj interface{}) (err error) {
    32  	q := c.GetAllQueryMaps()
    33  	typ := zreflect.TypeOf(obj)
    34  	m := make(map[string]interface{}, len(q))
    35  	err = zreflect.ForEach(typ, func(parent []string, index int, tag string, field reflect.StructField) error {
    36  		kind := field.Type.Kind()
    37  		if kind == reflect.Struct {
    38  			m[tag] = c.QueryMap(tag)
    39  		} else if kind == reflect.Slice {
    40  			v, _ := c.GetQueryArray(tag)
    41  			m[tag] = v
    42  		} else {
    43  			v, ok := q[tag]
    44  			if ok {
    45  				m[tag] = v
    46  			}
    47  		}
    48  
    49  		return zreflect.SkipChild
    50  	})
    51  	if err != nil {
    52  		return err
    53  	}
    54  	return ztype.ToStruct(m, obj)
    55  }
    56  
    57  func (c *Context) BindForm(obj interface{}) error {
    58  	q := c.GetPostFormAll()
    59  	typ := zreflect.TypeOf(obj)
    60  	m := make(map[string]interface{}, len(q))
    61  	err := zreflect.ForEach(typ, func(parent []string, index int, tag string, field reflect.StructField) error {
    62  		kind := field.Type.Kind()
    63  		if kind == reflect.Struct {
    64  			m[tag] = c.PostFormMap(tag)
    65  		} else if kind == reflect.Slice {
    66  			sliceTyp := field.Type.Elem().Kind()
    67  			if sliceTyp == reflect.Struct {
    68  				// TODO follow up support
    69  			} else {
    70  				m[tag], _ = q[tag]
    71  			}
    72  		} else {
    73  			v, ok := q[tag]
    74  			if ok {
    75  				m[tag] = v[0]
    76  			}
    77  		}
    78  
    79  		return zreflect.SkipChild
    80  	})
    81  	if err != nil {
    82  		return err
    83  	}
    84  	return ztype.ToStruct(m, obj)
    85  }