1
0

json.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package json
  2. import (
  3. "errors"
  4. "time"
  5. "github.com/imdario/mergo"
  6. "gogs.baozhida.cn/zoie/OAuth-core/config/encoder"
  7. "gogs.baozhida.cn/zoie/OAuth-core/config/encoder/json"
  8. "gogs.baozhida.cn/zoie/OAuth-core/config/reader"
  9. "gogs.baozhida.cn/zoie/OAuth-core/config/source"
  10. )
  11. const readerTyp = "json"
  12. type jsonReader struct {
  13. opts reader.Options
  14. json encoder.Encoder
  15. }
  16. func (j *jsonReader) Merge(changes ...*source.ChangeSet) (*source.ChangeSet, error) {
  17. var merged map[string]interface{}
  18. for _, m := range changes {
  19. if m == nil {
  20. continue
  21. }
  22. if len(m.Data) == 0 {
  23. continue
  24. }
  25. codec, ok := j.opts.Encoding[m.Format]
  26. if !ok {
  27. // fallback
  28. codec = j.json
  29. }
  30. var data map[string]interface{}
  31. if err := codec.Decode(m.Data, &data); err != nil {
  32. return nil, err
  33. }
  34. if err := mergo.Map(&merged, data, mergo.WithOverride); err != nil {
  35. return nil, err
  36. }
  37. }
  38. b, err := j.json.Encode(merged)
  39. if err != nil {
  40. return nil, err
  41. }
  42. cs := &source.ChangeSet{
  43. Timestamp: time.Now(),
  44. Data: b,
  45. Source: "json",
  46. Format: j.json.String(),
  47. }
  48. cs.Checksum = cs.Sum()
  49. return cs, nil
  50. }
  51. func (j *jsonReader) Values(ch *source.ChangeSet) (reader.Values, error) {
  52. if ch == nil {
  53. return nil, errors.New("changeset is nil")
  54. }
  55. if ch.Format != "json" {
  56. return nil, errors.New("unsupported format")
  57. }
  58. return newValues(ch)
  59. }
  60. func (j *jsonReader) String() string {
  61. return "json"
  62. }
  63. // NewReader creates a json reader
  64. func NewReader(opts ...reader.Option) reader.Reader {
  65. options := reader.NewOptions(opts...)
  66. return &jsonReader{
  67. json: json.NewEncoder(),
  68. opts: options,
  69. }
  70. }