dynmap.go 17 KB

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