github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/ztype/utils.go (about) 1 package ztype 2 3 import ( 4 "reflect" 5 "strconv" 6 7 "github.com/sohaha/zlsgo/zreflect" 8 ) 9 10 // GetType Get variable type 11 func GetType(s interface{}) string { 12 var varType string 13 switch s.(type) { 14 case int: 15 varType = "int" 16 case int8: 17 varType = "int8" 18 case int16: 19 varType = "int16" 20 case int32: 21 varType = "int32" 22 case int64: 23 varType = "int64" 24 case uint: 25 varType = "uint" 26 case uint8: 27 varType = "uint8" 28 case uint16: 29 varType = "uint16" 30 case uint32: 31 varType = "uint32" 32 case uint64: 33 varType = "uint64" 34 case float32: 35 varType = "float32" 36 case float64: 37 varType = "float64" 38 case bool: 39 varType = "bool" 40 case string: 41 varType = "string" 42 case []byte: 43 varType = "[]byte" 44 default: 45 if s == nil { 46 return "nil" 47 } 48 v := zreflect.TypeOf(s) 49 if v.Kind() == reflect.Invalid { 50 return "invalid" 51 } 52 varType = v.String() 53 } 54 return varType 55 } 56 57 func reflectPtr(r reflect.Value) reflect.Value { 58 if r.Kind() == reflect.Ptr { 59 r = r.Elem() 60 } 61 return r 62 } 63 64 func InArray(needle, hystack interface{}) bool { 65 nt := ToString(needle) 66 for _, item := range ToSlice(hystack) { 67 if nt == ToString(item) { 68 return true 69 } 70 } 71 return false 72 } 73 74 func parsePath(path string, v interface{}) (interface{}, bool) { 75 t := 0 76 i := 0 77 val := v 78 79 exist := true 80 pp := func(p string, v interface{}) (result interface{}) { 81 if v == nil || !exist { 82 return nil 83 } 84 85 switch val := v.(type) { 86 case Map: 87 result, exist = val[p] 88 case map[string]interface{}: 89 result, exist = val[p] 90 case map[string]string: 91 result, exist = val[p] 92 case map[string]int: 93 result, exist = val[p] 94 default: 95 vtyp := zreflect.TypeOf(v) 96 switch vtyp.Kind() { 97 case reflect.Map: 98 val := ToMap(v) 99 result, exist = val[p] 100 case reflect.Array, reflect.Slice: 101 i, err := strconv.Atoi(p) 102 if err == nil { 103 switch val := v.(type) { 104 case []Map: 105 if len(val) > i { 106 result = val[i] 107 } else { 108 exist = false 109 } 110 case []interface{}: 111 if len(val) > i { 112 result = val[i] 113 } else { 114 exist = false 115 } 116 case []string: 117 if len(val) > i { 118 result = val[i] 119 } else { 120 exist = false 121 } 122 default: 123 aval := ToSlice(v).Value() 124 if len(aval) > i { 125 result = aval[i] 126 } else { 127 exist = false 128 } 129 } 130 } 131 default: 132 133 } 134 } 135 136 return 137 } 138 139 for ; i < len(path); i++ { 140 switch path[i] { 141 case '\\': 142 ss := path[t:i] 143 i++ 144 path = ss + path[i:] 145 case '.': 146 val = pp(path[t:i], val) 147 t = i + 1 148 } 149 150 if !exist { 151 break 152 } 153 } 154 155 if i != t { 156 val = pp(path[t:], val) 157 } else if i == 0 && t == 0 { 158 val = pp(path, val) 159 } 160 161 return val, exist 162 }