map.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. package json
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "reflect"
  7. "strconv"
  8. )
  9. // Map type
  10. type Map map[string]interface{}
  11. // New init Map object
  12. func NewMap() Map {
  13. return make(Map)
  14. }
  15. // FromInterface convert map[string]interface{} or Map interface to Map
  16. func MapFromInterface(iface interface{}) (res Map) {
  17. switch val := iface.(type) {
  18. case map[string]interface{}:
  19. res = FromMap(val)
  20. case Map:
  21. res = val
  22. default:
  23. res = NewMap()
  24. }
  25. return
  26. }
  27. // FromMap convert map[string]interface{} to Map object
  28. func FromMap(m map[string]interface{}) Map {
  29. return Map(m)
  30. }
  31. // Bool returns bool value by key
  32. func (s Map) Bool(key string, defaultVal bool) bool {
  33. if res, check := s[key].(bool); check {
  34. return res
  35. }
  36. return defaultVal
  37. }
  38. // KeyExists check value exists by key
  39. func (s Map) KeyExists(key string) bool {
  40. _, check := s[key]
  41. return check
  42. }
  43. // KeysExists check values exists by keys list.
  44. // Returns the first blank key found.
  45. // If all keys are defined, an empty string will be returned
  46. func (s Map) KeysExists(keys []string) string {
  47. for _, key := range keys {
  48. if _, check := s[key]; !check {
  49. return key
  50. }
  51. }
  52. return ""
  53. }
  54. func val(l, r interface{}) (res reflect.Value) {
  55. lVal, rVal := reflect.ValueOf(l), reflect.ValueOf(r)
  56. if lVal.Kind() == reflect.Ptr && rVal.Kind() != reflect.Ptr {
  57. return val(lVal.Elem().Interface(), r)
  58. }
  59. defer func() {
  60. if r := recover(); r != nil {
  61. res = rVal
  62. }
  63. }()
  64. res = lVal.Convert(rVal.Type())
  65. return
  66. }
  67. func (s Map) IsInt(key string) bool {
  68. if iface, check := s[key]; check {
  69. rType := reflect.ValueOf(int(0)).Type()
  70. lType := reflect.ValueOf(iface).Type()
  71. //log.Println(rType, lType, reflect.ValueOf(iface).Convert(rType))
  72. return lType.ConvertibleTo(rType)
  73. }
  74. return false
  75. }
  76. // Int returns int64 value by key.
  77. // If key isn't defined will be returned defaultVal arg value
  78. func (s Map) Int(key string, defaultVal int64) int64 {
  79. if iface, check := s[key]; check {
  80. return val(iface, defaultVal).Int()
  81. }
  82. return defaultVal
  83. }
  84. func (s Map) Int32(key string, defaultVal int) int {
  85. if iface, check := s[key]; check {
  86. return val(iface, defaultVal).Interface().(int)
  87. }
  88. return defaultVal
  89. }
  90. // Value returns interface object with attempt to convert to defaultVal type.
  91. // If key isn't defined will be returned defaultVal arg value
  92. func (s Map) Value(key string, defaultVal interface{}) interface{} {
  93. // check value exists by key
  94. if iface, check := s[key]; check {
  95. // check defaultVal is valid
  96. dVal := reflect.ValueOf(defaultVal)
  97. if !dVal.IsValid() {
  98. // invalid, return arrived interface
  99. return iface
  100. }
  101. // defaultVal is valid, attempt to convert found value to defaultVal type
  102. lVal := reflect.ValueOf(iface)
  103. switch {
  104. case !lVal.IsValid():
  105. return defaultVal // invalid found value, return defaultVal
  106. case lVal.Kind() == dVal.Kind():
  107. return iface // types of found value and defaultVal is match. return found value
  108. case lVal.Type().ConvertibleTo(dVal.Type()):
  109. return lVal.Convert(dVal.Type()).Interface() // found value type can be converted to defaultVal type. return converted found value
  110. default:
  111. {
  112. // found value type can't be converted to defaultVal type. If found value is string, attempt to convert to number value
  113. if lVal.Kind() == reflect.String {
  114. switch dVal.Kind() {
  115. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  116. val, err := strconv.Atoi(lVal.String())
  117. if err != nil {
  118. return defaultVal
  119. }
  120. lVal = reflect.ValueOf(val)
  121. return lVal.Convert(dVal.Type())
  122. case reflect.Float32, reflect.Float64:
  123. val, err := strconv.ParseFloat(lVal.String(), 64)
  124. if err != nil {
  125. return defaultVal
  126. }
  127. lVal = reflect.ValueOf(val)
  128. return lVal.Convert(dVal.Type())
  129. }
  130. }
  131. }
  132. }
  133. }
  134. return defaultVal
  135. }
  136. // ValueJSON returns json source object by key
  137. // If key isn't defined will be returned defaultVal arg value
  138. func (s Map) ValueJSON(key string, defaultVal []byte) (res []byte) {
  139. res = defaultVal
  140. if s.KeyExists(key) {
  141. if r, err := json.Marshal(s[key]); err == nil {
  142. res = r
  143. }
  144. }
  145. return
  146. }
  147. // String returns string value by key
  148. // If key isn't defined will be returned defaultVal arg value
  149. func (s Map) String(key, defaultVal string) string {
  150. if iface, check := s[key]; check {
  151. return val(iface, defaultVal).String()
  152. }
  153. return defaultVal
  154. }
  155. func (s Map) EachSlice(key string, each func(int, any) bool) {
  156. sl := s.Slice(key, []any{})
  157. for i, val := range sl {
  158. if !each(i, val) {
  159. return
  160. }
  161. }
  162. }
  163. func (s Map) EachMap(key string, each func(int, Map) bool) {
  164. s.EachSlice(key, func(i int, val any) bool {
  165. switch val.(type) {
  166. case map[string]any:
  167. return each(i, Map(val.(map[string]any)))
  168. case Map:
  169. return each(i, val.(Map))
  170. default:
  171. return true
  172. }
  173. })
  174. }
  175. func (s Map) StringWithError(key, defaultVal string) (string, error) {
  176. if iface, check := s[key]; check {
  177. val := val(iface, defaultVal).String()
  178. if val == defaultVal {
  179. return defaultVal, fmt.Errorf("FIELD [%s] IS EMPTY", key)
  180. }
  181. return val, nil
  182. }
  183. return defaultVal, fmt.Errorf("FIELD [%s] IS NOT EXISTS", key)
  184. }
  185. func (s Map) Bytes(key string, defaultVal []byte) []byte {
  186. if iface, check := s[key]; check {
  187. return []byte(val(iface, defaultVal).String())
  188. }
  189. return defaultVal
  190. }
  191. func (s Map) BytesWithError(key string, defaultVal []byte) ([]byte, error) {
  192. if iface, check := s[key]; check {
  193. return []byte(val(iface, defaultVal).String()), nil
  194. }
  195. return defaultVal, fmt.Errorf("FIELD [%s] IS NOT EXISTS", key)
  196. }
  197. func (s Map) StringVal(key, defaultVal string) string {
  198. if iface, check := s[key]; check {
  199. return fmt.Sprint(iface)
  200. }
  201. return defaultVal
  202. }
  203. // Slce returns slice of interface{} by key
  204. // If key isn't defined or have a different type will be returned defaultVal arg value
  205. func (s Map) Slice(key string, defaultVal []interface{}) (res []interface{}) {
  206. if arr, check := s[key].([]interface{}); check {
  207. res = arr
  208. } else {
  209. res = defaultVal
  210. }
  211. return
  212. }
  213. // StringSlice returns string slice by key
  214. // If key isn't defined will be returned defaultVal arg value
  215. func (s Map) StringSlice(key string, defaultVal []string) (res []string) {
  216. if arr, check := s[key].([]interface{}); check {
  217. res = make([]string, len(arr))
  218. for i, v := range arr {
  219. res[i] = fmt.Sprint(v)
  220. }
  221. } else {
  222. res = defaultVal
  223. }
  224. return
  225. }
  226. // Map returns Map object by key
  227. // If key isn't defined or have other type will be returned defaultVal arg value
  228. func (s Map) Map(key string, defaultVal Map) (res Map) {
  229. val := s[key]
  230. switch iface := val.(type) {
  231. case Map:
  232. res = iface
  233. case map[string]interface{}:
  234. res = Map(iface)
  235. default:
  236. res = defaultVal
  237. }
  238. return
  239. }
  240. // JSON returns JSON source of the self object
  241. func (s Map) JSON() (res []byte) {
  242. res, _ = json.Marshal(s)
  243. return
  244. }
  245. // JSONIndent returns JSON source of the self object with indent
  246. func (s Map) JSONIndent(prefix, indent string) (res []byte) {
  247. res, _ = json.MarshalIndent(s, prefix, indent)
  248. return
  249. }
  250. func (s Map) JSONString() (res string) {
  251. if data, err := json.Marshal(s); err == nil {
  252. res = string(data)
  253. }
  254. return
  255. }
  256. func (s Map) JSONPrettyString() (res string) {
  257. if data, err := json.MarshalIndent(s, "", "\t"); err == nil {
  258. res = string(data)
  259. }
  260. return
  261. }
  262. func (s Map) LogPretty() {
  263. log.Println(s.JSONPrettyString())
  264. }
  265. // ToMap returns map[string]interface{} of the self object
  266. func (s Map) ToMap() map[string]interface{} { return map[string]interface{}(s) }
  267. // Copy returns copied map (todo dipcopy)
  268. func (s Map) Copy() (res Map) {
  269. res = make(Map)
  270. for key, val := range s {
  271. res[key] = val
  272. }
  273. return
  274. }
  275. func (s Map) IsEmpty() bool {
  276. return len(s) == 0
  277. }
  278. func (s Map) Update(m Map) {
  279. for key, val := range m {
  280. s[key] = val
  281. }
  282. }
  283. func (s Map) StorePtr(key string, val interface{}) interface{} {
  284. s[key] = &val
  285. return &val
  286. }
  287. func (s Map) Variable(key string, ptr interface{}) bool {
  288. val, check := s[key]
  289. if !check {
  290. // value is not exists
  291. return false
  292. }
  293. vVal := reflect.ValueOf(ptr)
  294. if vVal.Kind() != reflect.Ptr {
  295. // ptr is not a pointer
  296. return false
  297. }
  298. vElem := vVal.Elem()
  299. rVal := reflect.ValueOf(val)
  300. if !rVal.CanConvert(vElem.Type()) {
  301. // type is not converted
  302. return false
  303. }
  304. vElem.Set(rVal.Convert(vElem.Type()))
  305. return true
  306. }