dynmap.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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. // Private Get
  102. func (v *Value) get(key string) (*Value, error) {
  103. // Assume this is an object
  104. obj, err := v.Object()
  105. if err == nil {
  106. child, ok := obj.Map()[key]
  107. if ok {
  108. return child, nil
  109. } else {
  110. return nil, KeyNotFoundError{key}
  111. }
  112. }
  113. return nil, err
  114. }
  115. // Private get path
  116. func (v *Value) getPath(keys []string) (*Value, error) {
  117. current := v
  118. var err error
  119. for _, key := range keys {
  120. current, err = current.get(key)
  121. if err != nil {
  122. return nil, err
  123. }
  124. }
  125. return current, nil
  126. }
  127. // Gets the value at key path.
  128. // Returns error if the value does not exist.
  129. // Consider using the more specific Get<Type>(..) methods instead.
  130. // Example:
  131. // value, err := GetValue("address", "street")
  132. func (v *Object) GetValue(keys ...string) (*Value, error) {
  133. return v.getPath(keys)
  134. }
  135. // Gets the value at key path and attempts to typecast the value into an object.
  136. // Returns error if the value is not a json object.
  137. // Example:
  138. // object, err := GetObject("person", "address")
  139. func (v *Object) GetObject(keys ...string) (*Object, error) {
  140. child, err := v.getPath(keys)
  141. if err != nil {
  142. return nil, err
  143. } else {
  144. obj, err := child.Object()
  145. if err != nil {
  146. return nil, err
  147. } else {
  148. return obj, nil
  149. }
  150. }
  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. } else {
  161. return child.String()
  162. }
  163. }
  164. func (v *Object) MustGetString(path string, def string) string {
  165. keys := strings.Split(path, ".")
  166. if str, err := v.GetString(keys...); err != nil {
  167. return def
  168. } else {
  169. return str
  170. }
  171. }
  172. // Gets the value at key path and attempts to typecast the value into null.
  173. // Returns error if the value is not json null.
  174. // Example:
  175. // err := GetNull("address", "street")
  176. func (v *Object) GetNull(keys ...string) error {
  177. child, err := v.getPath(keys)
  178. if err != nil {
  179. return err
  180. }
  181. return child.Null()
  182. }
  183. // Gets the value at key path and attempts to typecast the value into a number.
  184. // Returns error if the value is not a json number.
  185. // Example:
  186. // n, err := GetNumber("address", "street_number")
  187. func (v *Object) GetNumber(keys ...string) (json.Number, error) {
  188. child, err := v.getPath(keys)
  189. if err != nil {
  190. return "", err
  191. } else {
  192. n, err := child.Number()
  193. if err != nil {
  194. return "", err
  195. } else {
  196. return n, nil
  197. }
  198. }
  199. }
  200. // Gets the value at key path and attempts to typecast the value into a float64.
  201. // Returns error if the value is not a json number.
  202. // Example:
  203. // n, err := GetNumber("address", "street_number")
  204. func (v *Object) GetFloat64(keys ...string) (float64, error) {
  205. child, err := v.getPath(keys)
  206. if err != nil {
  207. return 0, err
  208. } else {
  209. n, err := child.Float64()
  210. if err != nil {
  211. return 0, err
  212. } else {
  213. return n, nil
  214. }
  215. }
  216. }
  217. // Gets the value at key path and attempts to typecast the value into a float64.
  218. // Returns error if the value is not a json number.
  219. // Example:
  220. // n, err := GetNumber("address", "street_number")
  221. func (v *Object) GetInt64(keys ...string) (int64, error) {
  222. child, err := v.getPath(keys)
  223. if err != nil {
  224. return 0, err
  225. } else {
  226. n, err := child.Int64()
  227. if err != nil {
  228. return 0, err
  229. } else {
  230. return n, nil
  231. }
  232. }
  233. }
  234. // Gets the value at key path and attempts to typecast the value into a float64.
  235. // Returns error if the value is not a json number.
  236. // Example:
  237. // v, err := GetInterface("address", "anything")
  238. func (v *Object) GetInterface(keys ...string) (interface{}, error) {
  239. child, err := v.getPath(keys)
  240. if err != nil {
  241. return nil, err
  242. } else {
  243. return child.Interface(), nil
  244. }
  245. }
  246. // Gets the value at key path and attempts to typecast the value into a bool.
  247. // Returns error if the value is not a json boolean.
  248. // Example:
  249. // married, err := GetBoolean("person", "married")
  250. func (v *Object) GetBoolean(keys ...string) (bool, error) {
  251. child, err := v.getPath(keys)
  252. if err != nil {
  253. return false, err
  254. }
  255. return child.Boolean()
  256. }
  257. // Gets the value at key path and attempts to typecast the value into an array.
  258. // Returns error if the value is not a json array.
  259. // Consider using the more specific Get<Type>Array() since it may reduce later type casts.
  260. // Example:
  261. // friends, err := GetValueArray("person", "friends")
  262. // for i, friend := range friends {
  263. // ... // friend will be of type Value here
  264. // }
  265. func (v *Object) GetValueArray(keys ...string) ([]*Value, error) {
  266. child, err := v.getPath(keys)
  267. if err != nil {
  268. return nil, err
  269. } else {
  270. return child.Array()
  271. }
  272. }
  273. // Gets the value at key path and attempts to typecast the value into an array of objects.
  274. // Returns error if the value is not a json array or if any of the contained objects are not objects.
  275. // Example:
  276. // friends, err := GetObjectArray("person", "friends")
  277. // for i, friend := range friends {
  278. // ... // friend will be of type Object here
  279. // }
  280. func (v *Object) GetObjectArray(keys ...string) ([]*Object, error) {
  281. child, err := v.getPath(keys)
  282. if err != nil {
  283. return nil, err
  284. } else {
  285. array, err := child.Array()
  286. if err != nil {
  287. return nil, err
  288. } else {
  289. typedArray := make([]*Object, len(array))
  290. for index, arrayItem := range array {
  291. typedArrayItem, err := arrayItem.
  292. Object()
  293. if err != nil {
  294. return nil, err
  295. } else {
  296. typedArray[index] = typedArrayItem
  297. }
  298. }
  299. return typedArray, nil
  300. }
  301. }
  302. }
  303. // Gets the value at key path and attempts to typecast the value into an array of string.
  304. // Returns error if the value is not a json array or if any of the contained objects are not strings.
  305. // Gets the value at key path and attempts to typecast the value into an array of objects.
  306. // Returns error if the value is not a json array or if any of the contained objects are not objects.
  307. // Example:
  308. // friendNames, err := GetStringArray("person", "friend_names")
  309. // for i, friendName := range friendNames {
  310. // ... // friendName will be of type string here
  311. // }
  312. func (v *Object) GetStringArray(keys ...string) ([]string, error) {
  313. child, err := v.getPath(keys)
  314. if err != nil {
  315. return nil, err
  316. } else {
  317. array, err := child.Array()
  318. if err != nil {
  319. return nil, err
  320. } else {
  321. typedArray := make([]string, len(array))
  322. for index, arrayItem := range array {
  323. typedArrayItem, err := arrayItem.String()
  324. if err != nil {
  325. return nil, err
  326. } else {
  327. typedArray[index] = typedArrayItem
  328. }
  329. }
  330. return typedArray, nil
  331. }
  332. }
  333. }
  334. // Gets the value at key path and attempts to typecast the value into an array of numbers.
  335. // Returns error if the value is not a json array or if any of the contained objects are not numbers.
  336. // Example:
  337. // friendAges, err := GetNumberArray("person", "friend_ages")
  338. // for i, friendAge := range friendAges {
  339. // ... // friendAge will be of type float64 here
  340. // }
  341. func (v *Object) GetNumberArray(keys ...string) ([]json.Number, error) {
  342. child, err := v.getPath(keys)
  343. if err != nil {
  344. return nil, err
  345. } else {
  346. array, err := child.Array()
  347. if err != nil {
  348. return nil, err
  349. } else {
  350. typedArray := make([]json.Number, len(array))
  351. for index, arrayItem := range array {
  352. typedArrayItem, err := arrayItem.Number()
  353. if err != nil {
  354. return nil, err
  355. } else {
  356. typedArray[index] = typedArrayItem
  357. }
  358. }
  359. return typedArray, nil
  360. }
  361. }
  362. }
  363. // Gets the value at key path and attempts to typecast the value into an array of floats.
  364. // Returns error if the value is not a json array or if any of the contained objects are not numbers.
  365. func (v *Object) GetFloat64Array(keys ...string) ([]float64, error) {
  366. child, err := v.getPath(keys)
  367. if err != nil {
  368. return nil, err
  369. } else {
  370. array, err := child.Array()
  371. if err != nil {
  372. return nil, err
  373. } else {
  374. typedArray := make([]float64, len(array))
  375. for index, arrayItem := range array {
  376. typedArrayItem, err := arrayItem.Float64()
  377. if err != nil {
  378. return nil, err
  379. } else {
  380. typedArray[index] = typedArrayItem
  381. }
  382. }
  383. return typedArray, nil
  384. }
  385. }
  386. }
  387. // Gets the value at key path and attempts to typecast the value into an array of ints.
  388. // Returns error if the value is not a json array or if any of the contained objects are not numbers.
  389. func (v *Object) GetInt64Array(keys ...string) ([]int64, error) {
  390. child, err := v.getPath(keys)
  391. if err != nil {
  392. return nil, err
  393. } else {
  394. array, err := child.Array()
  395. if err != nil {
  396. return nil, err
  397. } else {
  398. typedArray := make([]int64, len(array))
  399. for index, arrayItem := range array {
  400. typedArrayItem, err := arrayItem.Int64()
  401. if err != nil {
  402. return nil, err
  403. } else {
  404. typedArray[index] = typedArrayItem
  405. }
  406. }
  407. return typedArray, nil
  408. }
  409. }
  410. }
  411. // Gets the value at key path and attempts to typecast the value into an array of bools.
  412. // Returns error if the value is not a json array or if any of the contained objects are not booleans.
  413. func (v *Object) GetBooleanArray(keys ...string) ([]bool, error) {
  414. child, err := v.getPath(keys)
  415. if err != nil {
  416. return nil, err
  417. } else {
  418. array, err := child.Array()
  419. if err != nil {
  420. return nil, err
  421. } else {
  422. typedArray := make([]bool, len(array))
  423. for index, arrayItem := range array {
  424. typedArrayItem, err := arrayItem.Boolean()
  425. if err != nil {
  426. return nil, err
  427. } else {
  428. typedArray[index] = typedArrayItem
  429. }
  430. }
  431. return typedArray, nil
  432. }
  433. }
  434. }
  435. // Gets the value at key path and attempts to typecast the value into an array of nulls.
  436. // Returns length, or an error if the value is not a json array or if any of the contained objects are not nulls.
  437. func (v *Object) GetNullArray(keys ...string) (int64, error) {
  438. child, err := v.getPath(keys)
  439. if err != nil {
  440. return 0, err
  441. } else {
  442. array, err := child.Array()
  443. if err != nil {
  444. return 0, err
  445. } else {
  446. var length int64 = 0
  447. for _, arrayItem := range array {
  448. err := arrayItem.Null()
  449. if err != nil {
  450. return 0, err
  451. } else {
  452. length++
  453. }
  454. }
  455. return length, nil
  456. }
  457. }
  458. }
  459. // Returns an error if the value is not actually null
  460. func (v *Value) Null() error {
  461. var valid bool
  462. // Check the type of this data
  463. switch v.data.(type) {
  464. case nil:
  465. valid = v.exists // Valid only if j also exists, since other values could possibly also be nil
  466. break
  467. }
  468. if valid {
  469. return nil
  470. }
  471. return ErrNotNull
  472. }
  473. // Attempts to typecast the current value into an array.
  474. // Returns error if the current value is not a json array.
  475. // Example:
  476. // friendsArray, err := friendsValue.Array()
  477. func (v *Value) Array() ([]*Value, error) {
  478. var valid bool
  479. // Check the type of this data
  480. switch v.data.(type) {
  481. case []interface{}:
  482. valid = true
  483. break
  484. }
  485. // Unsure if this is a good way to use slices, it's probably not
  486. var slice []*Value
  487. if valid {
  488. for _, element := range v.data.([]interface{}) {
  489. child := Value{element, true}
  490. slice = append(slice, &child)
  491. }
  492. return slice, nil
  493. }
  494. return slice, ErrNotArray
  495. }
  496. // Attempts to typecast the current value into a number.
  497. // Returns error if the current value is not a json number.
  498. // Example:
  499. // ageNumber, err := ageValue.Number()
  500. func (v *Value) Number() (json.Number, error) {
  501. var valid bool
  502. // Check the type of this data
  503. switch v.data.(type) {
  504. case json.Number:
  505. valid = true
  506. break
  507. }
  508. if valid {
  509. return v.data.(json.Number), nil
  510. }
  511. return "", ErrNotNumber
  512. }
  513. // Attempts to typecast the current value into a float64.
  514. // Returns error if the current value is not a json number.
  515. // Example:
  516. // percentage, err := v.Float64()
  517. func (v *Value) Float64() (float64, error) {
  518. n, err := v.Number()
  519. if err != nil {
  520. return 0, err
  521. }
  522. return n.Float64()
  523. }
  524. // Attempts to typecast the current value into a int64.
  525. // Returns error if the current value is not a json number.
  526. // Example:
  527. // id, err := v.Int64()
  528. func (v *Value) Int64() (int64, error) {
  529. n, err := v.Number()
  530. if err != nil {
  531. return 0, err
  532. }
  533. return n.Int64()
  534. }
  535. // Attempts to typecast the current value into a bool.
  536. // Returns error if the current value is not a json boolean.
  537. // Example:
  538. // marriedBool, err := marriedValue.Boolean()
  539. func (v *Value) Boolean() (bool, error) {
  540. var valid bool
  541. // Check the type of this data
  542. switch v.data.(type) {
  543. case bool:
  544. valid = true
  545. break
  546. }
  547. if valid {
  548. return v.data.(bool), nil
  549. }
  550. return false, ErrNotBool
  551. }
  552. // Attempts to typecast the current value into an object.
  553. // Returns error if the current value is not a json object.
  554. // Example:
  555. // friendObject, err := friendValue.Object()
  556. func (v *Value) Object() (*Object, error) {
  557. var valid bool
  558. // Check the type of this data
  559. switch v.data.(type) {
  560. case map[string]interface{}:
  561. valid = true
  562. break
  563. }
  564. if valid {
  565. obj := new(Object)
  566. obj.valid = valid
  567. m := make(map[string]*Value)
  568. if valid {
  569. for key, element := range v.data.(map[string]interface{}) {
  570. m[key] = &Value{element, true}
  571. }
  572. }
  573. obj.data = v.data
  574. obj.m = m
  575. return obj, nil
  576. }
  577. return nil, ErrNotObject
  578. }
  579. // Attempts to typecast the current value into an object arrau.
  580. // Returns error if the current value is not an array of json objects
  581. // Example:
  582. // friendObjects, err := friendValues.ObjectArray()
  583. func (v *Value) ObjectArray() ([]*Object, error) {
  584. var valid bool
  585. // Check the type of this data
  586. switch v.data.(type) {
  587. case []interface{}:
  588. valid = true
  589. break
  590. }
  591. // Unsure if this is a good way to use slices, it's probably not
  592. var slice []*Object
  593. if valid {
  594. for _, element := range v.data.([]interface{}) {
  595. childValue := Value{element, true}
  596. childObject, err := childValue.Object()
  597. if err != nil {
  598. return nil, ErrNotObjectArray
  599. }
  600. slice = append(slice, childObject)
  601. }
  602. return slice, nil
  603. }
  604. return nil, ErrNotObjectArray
  605. }
  606. // Attempts to typecast the current value into a string.
  607. // Returns error if the current value is not a json string
  608. // Example:
  609. // nameObject, err := nameValue.String()
  610. func (v *Value) String() (string, error) {
  611. var valid bool
  612. // Check the type of this data
  613. switch v.data.(type) {
  614. case string:
  615. valid = true
  616. break
  617. }
  618. if valid {
  619. return v.data.(string), nil
  620. }
  621. return "", ErrNotString
  622. }
  623. // Returns the value a json formatted string.
  624. // Note: The method named String() is used by golang's log method for logging.
  625. // Example:
  626. func (v *Object) String() string {
  627. f, err := json.Marshal(v.data)
  628. if err != nil {
  629. return err.Error()
  630. }
  631. return string(f)
  632. }
  633. func (v *Object) SetValue(key string, value interface{}) *Value {
  634. data := v.Interface().(map[string]interface{})
  635. data[key] = value
  636. return &Value{
  637. data: value,
  638. exists: true,
  639. }
  640. }