map.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 isType(l, r any) bool {
  68. if l == nil || r == nil {
  69. return false
  70. }
  71. rType := reflect.ValueOf(r).Type()
  72. lType := reflect.ValueOf(l).Type()
  73. //log.Println(rType, lType, reflect.ValueOf(iface).Convert(rType))
  74. return lType.ConvertibleTo(rType)
  75. }
  76. func (s Map) IsNil(key string) bool {
  77. if iface, check := s[key]; check {
  78. return iface == nil
  79. }
  80. return false
  81. }
  82. func (s Map) IsInt(key string) bool {
  83. if iface, check := s[key]; check {
  84. return isType(iface, int(0))
  85. }
  86. return false
  87. }
  88. func (s Map) IsBoolean(key string) bool {
  89. if iface, check := s[key]; check {
  90. return isType(iface, false)
  91. }
  92. return false
  93. }
  94. func (s Map) Byte(key string, defaultVal byte) byte {
  95. if iface, check := s[key]; check {
  96. return byte(val(iface, defaultVal).Int())
  97. }
  98. return defaultVal
  99. }
  100. // Int returns int64 value by key.
  101. // If key isn't defined will be returned defaultVal arg value
  102. func (s Map) Int(key string, defaultVal int64) int64 {
  103. if iface, check := s[key]; check {
  104. return val(iface, defaultVal).Int()
  105. }
  106. return defaultVal
  107. }
  108. func (s Map) Int32(key string, defaultVal int) int {
  109. if iface, check := s[key]; check {
  110. return val(iface, defaultVal).Interface().(int)
  111. }
  112. return defaultVal
  113. }
  114. func (s Map) Float32(key string, defaultVal float32) float32 {
  115. if iface, check := s[key]; check {
  116. return val(iface, defaultVal).Interface().(float32)
  117. }
  118. return defaultVal
  119. }
  120. func (s Map) Float64(key string, defaultVal float64) float64 {
  121. if iface, check := s[key]; check {
  122. return val(iface, defaultVal).Interface().(float64)
  123. }
  124. return defaultVal
  125. }
  126. // Value returns interface object with attempt to convert to defaultVal type.
  127. // If key isn't defined will be returned defaultVal arg value
  128. func (s Map) Value(key string, defaultVal interface{}) interface{} {
  129. // check value exists by key
  130. if iface, check := s[key]; check {
  131. // check defaultVal is valid
  132. dVal := reflect.ValueOf(defaultVal)
  133. if !dVal.IsValid() {
  134. // invalid, return arrived interface
  135. return iface
  136. }
  137. // defaultVal is valid, attempt to convert found value to defaultVal type
  138. lVal := reflect.ValueOf(iface)
  139. switch {
  140. case !lVal.IsValid():
  141. return defaultVal // invalid found value, return defaultVal
  142. case lVal.Kind() == dVal.Kind():
  143. return iface // types of found value and defaultVal is match. return found value
  144. case lVal.Type().ConvertibleTo(dVal.Type()):
  145. return lVal.Convert(dVal.Type()).Interface() // found value type can be converted to defaultVal type. return converted found value
  146. default:
  147. {
  148. // found value type can't be converted to defaultVal type. If found value is string, attempt to convert to number value
  149. if lVal.Kind() == reflect.String {
  150. switch dVal.Kind() {
  151. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  152. val, err := strconv.Atoi(lVal.String())
  153. if err != nil {
  154. return defaultVal
  155. }
  156. lVal = reflect.ValueOf(val)
  157. return lVal.Convert(dVal.Type())
  158. case reflect.Float32, reflect.Float64:
  159. val, err := strconv.ParseFloat(lVal.String(), 64)
  160. if err != nil {
  161. return defaultVal
  162. }
  163. lVal = reflect.ValueOf(val)
  164. return lVal.Convert(dVal.Type())
  165. }
  166. }
  167. }
  168. }
  169. }
  170. return defaultVal
  171. }
  172. // ValueJSON returns json source object by key
  173. // If key isn't defined will be returned defaultVal arg value
  174. func (s Map) ValueJSON(key string, defaultVal []byte) (res []byte) {
  175. res = defaultVal
  176. if s.KeyExists(key) {
  177. if r, err := json.Marshal(s[key]); err == nil {
  178. res = r
  179. }
  180. }
  181. return
  182. }
  183. // String returns string value by key
  184. // If key isn't defined will be returned defaultVal arg value
  185. func (s Map) String(key, defaultVal string) string {
  186. if iface, check := s[key]; check {
  187. return val(iface, defaultVal).String()
  188. }
  189. return defaultVal
  190. }
  191. func (s Map) EachSlice(key string, each func(int, any) bool) {
  192. sl := s.Slice(key, []any{})
  193. for i, val := range sl {
  194. if !each(i, val) {
  195. return
  196. }
  197. }
  198. }
  199. func (s Map) EachMap(key string, each func(int, Map) bool) {
  200. s.EachSlice(key, func(i int, val any) bool {
  201. switch val.(type) {
  202. case map[string]any:
  203. return each(i, Map(val.(map[string]any)))
  204. case Map:
  205. return each(i, val.(Map))
  206. default:
  207. return true
  208. }
  209. })
  210. }
  211. func (s Map) StringWithError(key, defaultVal string) (string, error) {
  212. if iface, check := s[key]; check {
  213. val := val(iface, defaultVal).String()
  214. if val == defaultVal {
  215. return defaultVal, fmt.Errorf("FIELD [%s] IS EMPTY", key)
  216. }
  217. return val, nil
  218. }
  219. return defaultVal, fmt.Errorf("FIELD [%s] IS NOT EXISTS", key)
  220. }
  221. func (s Map) Bytes(key string, defaultVal []byte) []byte {
  222. if iface, check := s[key]; check {
  223. return []byte(val(iface, defaultVal).String())
  224. }
  225. return defaultVal
  226. }
  227. func (s Map) BytesWithError(key string, defaultVal []byte) ([]byte, error) {
  228. if iface, check := s[key]; check {
  229. return []byte(val(iface, defaultVal).String()), nil
  230. }
  231. return defaultVal, fmt.Errorf("FIELD [%s] IS NOT EXISTS", key)
  232. }
  233. func (s Map) StringVal(key, defaultVal string) string {
  234. if iface, check := s[key]; check {
  235. return fmt.Sprint(iface)
  236. }
  237. return defaultVal
  238. }
  239. // Slce returns slice of interface{} by key
  240. // If key isn't defined or have a different type will be returned defaultVal arg value
  241. func (s Map) Slice(key string, defaultVal []interface{}) (res []interface{}) {
  242. if arr, check := s[key].([]interface{}); check {
  243. res = arr
  244. } else {
  245. res = defaultVal
  246. }
  247. return
  248. }
  249. // StringSlice returns string slice by key
  250. // If key isn't defined will be returned defaultVal arg value
  251. func (s Map) StringSlice(key string, defaultVal []string) (res []string) {
  252. if arr, check := s[key].([]interface{}); check {
  253. res = make([]string, len(arr))
  254. for i, v := range arr {
  255. res[i] = fmt.Sprint(v)
  256. }
  257. } else {
  258. res = defaultVal
  259. }
  260. return
  261. }
  262. // Map returns Map object by key
  263. // If key isn't defined or have other type will be returned defaultVal arg value
  264. func (s Map) Map(key string, defaultVal Map) (res Map) {
  265. val := s[key]
  266. switch iface := val.(type) {
  267. case Map:
  268. res = iface
  269. case map[string]interface{}:
  270. res = Map(iface)
  271. default:
  272. res = defaultVal
  273. }
  274. return
  275. }
  276. // JSON returns JSON source of the self object
  277. func (s Map) JSON() (res []byte) {
  278. res, _ = json.Marshal(s)
  279. return
  280. }
  281. // JSONIndent returns JSON source of the self object with indent
  282. func (s Map) JSONIndent(prefix, indent string) (res []byte) {
  283. res, _ = json.MarshalIndent(s, prefix, indent)
  284. return
  285. }
  286. func (s Map) JSONString() (res string) {
  287. if data, err := json.Marshal(s); err == nil {
  288. res = string(data)
  289. }
  290. return
  291. }
  292. func (s Map) JSONPrettyString() (res string) {
  293. if data, err := json.MarshalIndent(s, "", "\t"); err == nil {
  294. res = string(data)
  295. }
  296. return
  297. }
  298. func (s Map) LogPretty() {
  299. log.Println(s.JSONPrettyString())
  300. }
  301. // ToMap returns map[string]interface{} of the self object
  302. func (s Map) ToMap() map[string]interface{} { return map[string]interface{}(s) }
  303. // Copy returns copied map (todo dipcopy)
  304. func (s Map) Copy() (res Map) {
  305. res = make(Map)
  306. for key, val := range s {
  307. res[key] = val
  308. }
  309. return
  310. }
  311. func (s Map) IsEmpty() bool {
  312. return len(s) == 0
  313. }
  314. func (s Map) Update(m Map) {
  315. for key, val := range m {
  316. s[key] = val
  317. }
  318. }
  319. func (s Map) StorePtr(key string, val interface{}) interface{} {
  320. s[key] = &val
  321. return &val
  322. }
  323. func (s Map) Variable(key string, ptr interface{}) bool {
  324. val, check := s[key]
  325. if !check {
  326. // value is not exists
  327. return false
  328. }
  329. vVal := reflect.ValueOf(ptr)
  330. if vVal.Kind() != reflect.Ptr {
  331. // ptr is not a pointer
  332. return false
  333. }
  334. vElem := vVal.Elem()
  335. rVal := reflect.ValueOf(val)
  336. if !rVal.CanConvert(vElem.Type()) {
  337. // type is not converted
  338. return false
  339. }
  340. vElem.Set(rVal.Convert(vElem.Type()))
  341. return true
  342. }