dynmap.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. // uses code from https://github.com/antonholmquist/jason/blob/master/jason.go
  2. // MIT Licence
  3. package dynmap
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "strings"
  11. )
  12. // Error values returned when validation functions fail
  13. var (
  14. ErrNotNull = errors.New("is not null")
  15. ErrNotArray = errors.New("Not an array")
  16. ErrNotNumber = errors.New("not a number")
  17. ErrNotBool = errors.New("no bool")
  18. ErrNotObject = errors.New("not an object")
  19. ErrNotObjectArray = errors.New("not an object array")
  20. ErrNotString = errors.New("not a string")
  21. )
  22. type KeyNotFoundError struct {
  23. Key string
  24. }
  25. func (k KeyNotFoundError) Error() string {
  26. if k.Key != "" {
  27. return fmt.Sprintf("key '%s' not found", k.Key)
  28. }
  29. return "key not found"
  30. }
  31. // Value represents an arbitrary JSON value.
  32. // It may contain a bool, number, string, object, array or null.
  33. type Value struct {
  34. data interface{}
  35. exists bool // Used to separate nil and non-existing values
  36. }
  37. // Object represents an object JSON object.
  38. // It inherets from Value but with an additional method to access
  39. // a map representation of it's content. It's useful when iterating.
  40. type Object struct {
  41. Value
  42. m map[string]*Value
  43. valid bool
  44. }
  45. // Returns the golang map.
  46. // Needed when iterating through the values of the object.
  47. func (v *Object) Map() map[string]*Value {
  48. return v.m
  49. }
  50. func NewFromMap(data map[string]interface{}) *Object {
  51. val := &Value{data: data, exists: true}
  52. obj, _ := val.Object()
  53. return obj
  54. }
  55. func NewObject() *Object {
  56. val := &Value{data: make(map[string]interface{}), exists: true}
  57. obj, _ := val.Object()
  58. return obj
  59. }
  60. // Creates a new value from an io.reader.
  61. // Returns an error if the reader does not contain valid json.
  62. // Useful for parsing the body of a net/http response.
  63. // Example: NewFromReader(res.Body)
  64. func NewValueFromReader(reader io.Reader) (*Value, error) {
  65. j := new(Value)
  66. d := json.NewDecoder(reader)
  67. d.UseNumber()
  68. err := d.Decode(&j.data)
  69. return j, err
  70. }
  71. // Creates a new value from bytes.
  72. // Returns an error if the bytes are not valid json.
  73. func NewValueFromBytes(b []byte) (*Value, error) {
  74. r := bytes.NewReader(b)
  75. return NewValueFromReader(r)
  76. }
  77. func objectFromValue(v *Value, err error) (*Object, error) {
  78. if err != nil {
  79. return nil, err
  80. }
  81. o, err := v.Object()
  82. if err != nil {
  83. return nil, err
  84. }
  85. return o, nil
  86. }
  87. func NewObjectFromBytes(b []byte) (*Object, error) {
  88. return objectFromValue(NewValueFromBytes(b))
  89. }
  90. func NewObjectFromReader(reader io.Reader) (*Object, error) {
  91. return objectFromValue(NewValueFromReader(reader))
  92. }
  93. // Marshal into bytes.
  94. func (v *Value) Marshal() ([]byte, error) {
  95. return json.Marshal(v.data)
  96. }
  97. // Get the interyling data as interface
  98. func (v *Value) Interface() interface{} {
  99. return v.data
  100. }
  101. func (v *Value) StringMap() map[string]interface{} {
  102. return v.data.(map[string]interface{})
  103. }
  104. // Private Get
  105. func (v *Value) get(key string) (*Value, error) {
  106. // Assume this is an object
  107. obj, err := v.Object()
  108. if err == nil {
  109. child, ok := obj.Map()[key]
  110. if ok {
  111. return child, nil
  112. }
  113. return nil, KeyNotFoundError{key}
  114. }
  115. return nil, err
  116. }
  117. // Private get path
  118. func (v *Value) getPath(keys []string) (*Value, error) {
  119. current := v
  120. var err error
  121. for _, key := range keys {
  122. current, err = current.get(key)
  123. if err != nil {
  124. return nil, err
  125. }
  126. }
  127. return current, nil
  128. }
  129. // Gets the value at key path.
  130. // Returns error if the value does not exist.
  131. // Consider using the more specific Get<Type>(..) methods instead.
  132. // Example:
  133. // value, err := GetValue("address", "street")
  134. func (v *Object) GetValue(keys ...string) (*Value, error) {
  135. return v.getPath(keys)
  136. }
  137. // Gets the value at key path and attempts to typecast the value into an object.
  138. // Returns error if the value is not a json object.
  139. // Example:
  140. // object, err := GetObject("person", "address")
  141. func (v *Object) GetObject(keys ...string) (*Object, error) {
  142. child, err := v.getPath(keys)
  143. if err != nil {
  144. return nil, err
  145. }
  146. obj, err := child.Object()
  147. if err != nil {
  148. return nil, err
  149. }
  150. return obj, nil
  151. }
  152. // Gets the value at key path and attempts to typecast the value into a string.
  153. // Returns error if the value is not a json string.
  154. // Example:
  155. // string, err := GetString("address", "street")
  156. func (v *Object) GetString(keys ...string) (string, error) {
  157. child, err := v.getPath(keys)
  158. if err != nil {
  159. return "", err
  160. }
  161. return child.String()
  162. }
  163. func (v *Object) MustGetString(path string, def string) string {
  164. keys := strings.Split(path, ".")
  165. str, err := v.GetString(keys...)
  166. if err != nil {
  167. return def
  168. }
  169. return str
  170. }
  171. // Gets the value at key path and attempts to typecast the value into null.
  172. // Returns error if the value is not json null.
  173. // Example:
  174. // err := GetNull("address", "street")
  175. func (v *Object) GetNull(keys ...string) error {
  176. child, err := v.getPath(keys)
  177. if err != nil {
  178. return err
  179. }
  180. return child.Null()
  181. }
  182. // Gets the value at key path and attempts to typecast the value into a number.
  183. // Returns error if the value is not a json number.
  184. // Example:
  185. // n, err := GetNumber("address", "street_number")
  186. func (v *Object) GetNumber(keys ...string) (json.Number, error) {
  187. child, err := v.getPath(keys)
  188. if err != nil {
  189. return "", err
  190. }
  191. n, err := child.Number()
  192. if err != nil {
  193. return "", err
  194. }
  195. return n, nil
  196. }
  197. // Gets the value at key path and attempts to typecast the value into a float64.
  198. // Returns error if the value is not a json number.
  199. // Example:
  200. // n, err := GetNumber("address", "street_number")
  201. func (v *Object) GetFloat64(keys ...string) (float64, error) {
  202. child, err := v.getPath(keys)
  203. if err != nil {
  204. return 0, err
  205. }
  206. n, err := child.Float64()
  207. if err != nil {
  208. return 0, err
  209. }
  210. return n, nil
  211. }
  212. // Gets the value at key path and attempts to typecast the value into a float64.
  213. // Returns error if the value is not a json number.
  214. // Example:
  215. // n, err := GetNumber("address", "street_number")
  216. func (v *Object) GetInt64(keys ...string) (int64, error) {
  217. child, err := v.getPath(keys)
  218. if err != nil {
  219. return 0, err
  220. }
  221. n, err := child.Int64()
  222. if err != nil {
  223. return 0, err
  224. }
  225. return n, nil
  226. }
  227. // Gets the value at key path and attempts to typecast the value into a float64.
  228. // Returns error if the value is not a json number.
  229. // Example:
  230. // v, err := GetInterface("address", "anything")
  231. func (v *Object) GetInterface(keys ...string) (interface{}, error) {
  232. child, err := v.getPath(keys)
  233. if err != nil {
  234. return nil, err
  235. }
  236. return child.Interface(), nil
  237. }
  238. // Gets the value at key path and attempts to typecast the value into a bool.
  239. // Returns error if the value is not a json boolean.
  240. // Example:
  241. // married, err := GetBoolean("person", "married")
  242. func (v *Object) GetBoolean(keys ...string) (bool, error) {
  243. child, err := v.getPath(keys)
  244. if err != nil {
  245. return false, err
  246. }
  247. return child.Boolean()
  248. }
  249. // Gets the value at key path and attempts to typecast the value into an array.
  250. // Returns error if the value is not a json array.
  251. // Consider using the more specific Get<Type>Array() since it may reduce later type casts.
  252. // Example:
  253. // friends, err := GetValueArray("person", "friends")
  254. // for i, friend := range friends {
  255. // ... // friend will be of type Value here
  256. // }
  257. func (v *Object) GetValueArray(keys ...string) ([]*Value, error) {
  258. child, err := v.getPath(keys)
  259. if err != nil {
  260. return nil, err
  261. }
  262. return child.Array()
  263. }
  264. // Gets the value at key path and attempts to typecast the value into an array of objects.
  265. // Returns error if the value is not a json array or if any of the contained objects are not objects.
  266. // Example:
  267. // friends, err := GetObjectArray("person", "friends")
  268. // for i, friend := range friends {
  269. // ... // friend will be of type Object here
  270. // }
  271. func (v *Object) GetObjectArray(keys ...string) ([]*Object, error) {
  272. child, err := v.getPath(keys)
  273. if err != nil {
  274. return nil, err
  275. }
  276. array, err := child.Array()
  277. if err != nil {
  278. return nil, err
  279. }
  280. typedArray := make([]*Object, len(array))
  281. for index, arrayItem := range array {
  282. typedArrayItem, err := arrayItem.
  283. Object()
  284. if err != nil {
  285. return nil, err
  286. }
  287. typedArray[index] = typedArrayItem
  288. }
  289. return typedArray, nil
  290. }
  291. // Gets the value at key path and attempts to typecast the value into an array of string.
  292. // Returns error if the value is not a json array or if any of the contained objects are not strings.
  293. // Gets the value at key path and attempts to typecast the value into an array of objects.
  294. // Returns error if the value is not a json array or if any of the contained objects are not objects.
  295. // Example:
  296. // friendNames, err := GetStringArray("person", "friend_names")
  297. // for i, friendName := range friendNames {
  298. // ... // friendName will be of type string here
  299. // }
  300. func (v *Object) GetStringArray(keys ...string) ([]string, error) {
  301. child, err := v.getPath(keys)
  302. if err != nil {
  303. return nil, err
  304. }
  305. array, err := child.Array()
  306. if err != nil {
  307. return nil, err
  308. }
  309. typedArray := make([]string, len(array))
  310. for index, arrayItem := range array {
  311. typedArrayItem, err := arrayItem.String()
  312. if err != nil {
  313. return nil, err
  314. }
  315. typedArray[index] = typedArrayItem
  316. }
  317. return typedArray, nil
  318. }
  319. // Gets the value at key path and attempts to typecast the value into an array of numbers.
  320. // Returns error if the value is not a json array or if any of the contained objects are not numbers.
  321. // Example:
  322. // friendAges, err := GetNumberArray("person", "friend_ages")
  323. // for i, friendAge := range friendAges {
  324. // ... // friendAge will be of type float64 here
  325. // }
  326. func (v *Object) GetNumberArray(keys ...string) ([]json.Number, error) {
  327. child, err := v.getPath(keys)
  328. if err != nil {
  329. return nil, err
  330. }
  331. array, err := child.Array()
  332. if err != nil {
  333. return nil, err
  334. }
  335. typedArray := make([]json.Number, len(array))
  336. for index, arrayItem := range array {
  337. typedArrayItem, err := arrayItem.Number()
  338. if err != nil {
  339. return nil, err
  340. }
  341. typedArray[index] = typedArrayItem
  342. }
  343. return typedArray, nil
  344. }
  345. // Gets the value at key path and attempts to typecast the value into an array of floats.
  346. // Returns error if the value is not a json array or if any of the contained objects are not numbers.
  347. func (v *Object) GetFloat64Array(keys ...string) ([]float64, error) {
  348. child, err := v.getPath(keys)
  349. if err != nil {
  350. return nil, err
  351. }
  352. array, err := child.Array()
  353. if err != nil {
  354. return nil, err
  355. }
  356. typedArray := make([]float64, len(array))
  357. for index, arrayItem := range array {
  358. typedArrayItem, err := arrayItem.Float64()
  359. if err != nil {
  360. return nil, err
  361. }
  362. typedArray[index] = typedArrayItem
  363. }
  364. return typedArray, nil
  365. }
  366. // Gets the value at key path and attempts to typecast the value into an array of ints.
  367. // Returns error if the value is not a json array or if any of the contained objects are not numbers.
  368. func (v *Object) GetInt64Array(keys ...string) ([]int64, error) {
  369. child, err := v.getPath(keys)
  370. if err != nil {
  371. return nil, err
  372. }
  373. array, err := child.Array()
  374. if err != nil {
  375. return nil, err
  376. }
  377. typedArray := make([]int64, len(array))
  378. for index, arrayItem := range array {
  379. typedArrayItem, err := arrayItem.Int64()
  380. if err != nil {
  381. return nil, err
  382. }
  383. typedArray[index] = typedArrayItem
  384. }
  385. return typedArray, nil
  386. }
  387. // Gets the value at key path and attempts to typecast the value into an array of bools.
  388. // Returns error if the value is not a json array or if any of the contained objects are not booleans.
  389. func (v *Object) GetBooleanArray(keys ...string) ([]bool, error) {
  390. child, err := v.getPath(keys)
  391. if err != nil {
  392. return nil, err
  393. }
  394. array, err := child.Array()
  395. if err != nil {
  396. return nil, err
  397. }
  398. typedArray := make([]bool, len(array))
  399. for index, arrayItem := range array {
  400. typedArrayItem, err := arrayItem.Boolean()
  401. if err != nil {
  402. return nil, err
  403. }
  404. typedArray[index] = typedArrayItem
  405. }
  406. return typedArray, nil
  407. }
  408. // Gets the value at key path and attempts to typecast the value into an array of nulls.
  409. // Returns length, or an error if the value is not a json array or if any of the contained objects are not nulls.
  410. func (v *Object) GetNullArray(keys ...string) (int64, error) {
  411. child, err := v.getPath(keys)
  412. if err != nil {
  413. return 0, err
  414. }
  415. array, err := child.Array()
  416. if err != nil {
  417. return 0, err
  418. }
  419. var length int64 = 0
  420. for _, arrayItem := range array {
  421. err := arrayItem.Null()
  422. if err != nil {
  423. return 0, err
  424. }
  425. length++
  426. }
  427. return length, nil
  428. }
  429. // Returns an error if the value is not actually null
  430. func (v *Value) Null() error {
  431. var valid bool
  432. // Check the type of this data
  433. switch v.data.(type) {
  434. case nil:
  435. valid = v.exists // Valid only if j also exists, since other values could possibly also be nil
  436. }
  437. if valid {
  438. return nil
  439. }
  440. return ErrNotNull
  441. }
  442. // Attempts to typecast the current value into an array.
  443. // Returns error if the current value is not a json array.
  444. // Example:
  445. // friendsArray, err := friendsValue.Array()
  446. func (v *Value) Array() ([]*Value, error) {
  447. var valid bool
  448. // Check the type of this data
  449. switch v.data.(type) {
  450. case []interface{}:
  451. valid = true
  452. }
  453. // Unsure if this is a good way to use slices, it's probably not
  454. var slice []*Value
  455. if valid {
  456. for _, element := range v.data.([]interface{}) {
  457. child := Value{element, true}
  458. slice = append(slice, &child)
  459. }
  460. return slice, nil
  461. }
  462. return slice, ErrNotArray
  463. }
  464. // Attempts to typecast the current value into a number.
  465. // Returns error if the current value is not a json number.
  466. // Example:
  467. // ageNumber, err := ageValue.Number()
  468. func (v *Value) Number() (json.Number, error) {
  469. var valid bool
  470. // Check the type of this data
  471. switch v.data.(type) {
  472. case json.Number:
  473. valid = true
  474. }
  475. if valid {
  476. return v.data.(json.Number), nil
  477. }
  478. return "", ErrNotNumber
  479. }
  480. // Attempts to typecast the current value into a float64.
  481. // Returns error if the current value is not a json number.
  482. // Example:
  483. // percentage, err := v.Float64()
  484. func (v *Value) Float64() (float64, error) {
  485. n, err := v.Number()
  486. if err != nil {
  487. return 0, err
  488. }
  489. return n.Float64()
  490. }
  491. // Attempts to typecast the current value into a int64.
  492. // Returns error if the current value is not a json number.
  493. // Example:
  494. // id, err := v.Int64()
  495. func (v *Value) Int64() (int64, error) {
  496. n, err := v.Number()
  497. if err != nil {
  498. return 0, err
  499. }
  500. return n.Int64()
  501. }
  502. // Attempts to typecast the current value into a bool.
  503. // Returns error if the current value is not a json boolean.
  504. // Example:
  505. // marriedBool, err := marriedValue.Boolean()
  506. func (v *Value) Boolean() (bool, error) {
  507. var valid bool
  508. // Check the type of this data
  509. switch v.data.(type) {
  510. case bool:
  511. valid = true
  512. }
  513. if valid {
  514. return v.data.(bool), nil
  515. }
  516. return false, ErrNotBool
  517. }
  518. // Attempts to typecast the current value into an object.
  519. // Returns error if the current value is not a json object.
  520. // Example:
  521. // friendObject, err := friendValue.Object()
  522. func (v *Value) Object() (*Object, error) {
  523. var valid bool
  524. // Check the type of this data
  525. switch v.data.(type) {
  526. case map[string]interface{}:
  527. valid = true
  528. }
  529. if valid {
  530. obj := new(Object)
  531. obj.valid = valid
  532. m := make(map[string]*Value)
  533. if valid {
  534. for key, element := range v.data.(map[string]interface{}) {
  535. m[key] = &Value{element, true}
  536. }
  537. }
  538. obj.data = v.data
  539. obj.m = m
  540. return obj, nil
  541. }
  542. return nil, ErrNotObject
  543. }
  544. // Attempts to typecast the current value into an object arrau.
  545. // Returns error if the current value is not an array of json objects
  546. // Example:
  547. // friendObjects, err := friendValues.ObjectArray()
  548. func (v *Value) ObjectArray() ([]*Object, error) {
  549. var valid bool
  550. // Check the type of this data
  551. switch v.data.(type) {
  552. case []interface{}:
  553. valid = true
  554. }
  555. // Unsure if this is a good way to use slices, it's probably not
  556. var slice []*Object
  557. if valid {
  558. for _, element := range v.data.([]interface{}) {
  559. childValue := Value{element, true}
  560. childObject, err := childValue.Object()
  561. if err != nil {
  562. return nil, ErrNotObjectArray
  563. }
  564. slice = append(slice, childObject)
  565. }
  566. return slice, nil
  567. }
  568. return nil, ErrNotObjectArray
  569. }
  570. // Attempts to typecast the current value into a string.
  571. // Returns error if the current value is not a json string
  572. // Example:
  573. // nameObject, err := nameValue.String()
  574. func (v *Value) String() (string, error) {
  575. var valid bool
  576. // Check the type of this data
  577. switch v.data.(type) {
  578. case string:
  579. valid = true
  580. }
  581. if valid {
  582. return v.data.(string), nil
  583. }
  584. return "", ErrNotString
  585. }
  586. // Returns the value a json formatted string.
  587. // Note: The method named String() is used by golang's log method for logging.
  588. // Example:
  589. func (v *Object) String() string {
  590. f, err := json.Marshal(v.data)
  591. if err != nil {
  592. return err.Error()
  593. }
  594. return string(f)
  595. }
  596. func (v *Object) SetValue(key string, value interface{}) *Value {
  597. data := v.Interface().(map[string]interface{})
  598. data[key] = value
  599. return &Value{
  600. data: value,
  601. exists: true,
  602. }
  603. }