github.com/zooyer/miskit@v1.0.71/utils/type.go (about)

     1  /**
     2   * @Author: zzy
     3   * @Email: zhangzhongyuan@didiglobal.com
     4   * @Description:
     5   * @File: type.go
     6   * @Package: utils
     7   * @Version: 1.0.0
     8   * @Date: 2022/6/13 15:30
     9   */
    10  
    11  package utils
    12  
    13  import (
    14  	"reflect"
    15  	"strings"
    16  )
    17  
    18  func parseTag(tag string) (name string, options string) {
    19  	if idx := strings.Index(tag, ","); idx != -1 {
    20  		return tag[:idx], tag[idx+1:]
    21  	}
    22  	return tag, ""
    23  }
    24  
    25  // StructToMap 结构体转map
    26  func StructToMap(v interface{}, tag string) map[string]interface{} {
    27  	var (
    28  		val    = reflect.ValueOf(v)
    29  		typ    = val.Type()
    30  		fields = make(map[string]interface{})
    31  	)
    32  
    33  	for i := 0; i < typ.NumField(); i++ {
    34  		if typ.Field(i).Anonymous {
    35  			for key, val := range StructToMap(val.Field(i).Interface(), tag) {
    36  				fields[key] = val
    37  			}
    38  			continue
    39  		}
    40  
    41  		if tag == "" {
    42  			fields[typ.Field(i).Name] = val.Field(i).Interface()
    43  			continue
    44  		}
    45  
    46  		tag := typ.Field(i).Tag.Get(tag)
    47  		name, options := parseTag(tag)
    48  		if val.Field(i).IsZero() && strings.Contains(options, "omitempty") {
    49  			continue
    50  		}
    51  
    52  		fields[name] = val.Field(i).Interface()
    53  	}
    54  
    55  	return fields
    56  }