3 Star 5 Fork 3

三三物联网/ssiot-core

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
json.go 1.62 KB
Copy Edit Raw Blame History
三三物联网 authored 2023-04-03 00:22 . 重构
package json
import (
"errors"
"gitee.com/sansaniot/ssiot-core/config/tool/encoder"
"gitee.com/sansaniot/ssiot-core/config/tool/encoder/json"
reader2 "gitee.com/sansaniot/ssiot-core/config/tool/reader"
"gitee.com/sansaniot/ssiot-core/config/tool/source"
"time"
"github.com/imdario/mergo"
)
const readerTyp = "json"
type jsonReader struct {
opts reader2.Options
json encoder.Encoder
}
func (j *jsonReader) Merge(changes ...*source.ChangeSet) (*source.ChangeSet, error) {
var merged map[string]interface{}
for _, m := range changes {
if m == nil {
continue
}
if len(m.Data) == 0 {
continue
}
codec, ok := j.opts.Encoding[m.Format]
if !ok {
// fallback
codec = j.json
}
var data map[string]interface{}
if err := codec.Decode(m.Data, &data); err != nil {
return nil, err
}
if err := mergo.Map(&merged, data, mergo.WithOverride); err != nil {
return nil, err
}
}
b, err := j.json.Encode(merged)
if err != nil {
return nil, err
}
cs := &source.ChangeSet{
Timestamp: time.Now(),
Data: b,
Source: "json",
Format: j.json.String(),
}
cs.Checksum = cs.Sum()
return cs, nil
}
func (j *jsonReader) Values(ch *source.ChangeSet) (reader2.Values, error) {
if ch == nil {
return nil, errors.New("changeset is nil")
}
if ch.Format != "json" {
return nil, errors.New("unsupported format")
}
return newValues(ch)
}
func (j *jsonReader) String() string {
return "json"
}
// NewReader creates a json reader
func NewReader(opts ...reader2.Option) reader2.Reader {
options := reader2.NewOptions(opts...)
return &jsonReader{
json: json.NewEncoder(),
opts: options,
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/sansaniot/ssiot-core.git
git@gitee.com:sansaniot/ssiot-core.git
sansaniot
ssiot-core
ssiot-core
v1.7.8

Search