This repository has been archived by the owner on Oct 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjson_inline.go
209 lines (193 loc) · 4.17 KB
/
json_inline.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// json_inline.go
package libwimark
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
ms "github.com/mitchellh/mapstructure"
deepcopy "github.com/mohae/deepcopy"
)
type inlineTag struct {
Enabled bool
Unique bool
Omitempty bool
Attrs map[string]string
Key string
Name string
}
func parseInlineTag(tag string) inlineTag {
var res = inlineTag{Attrs: map[string]string{}}
var keys = []string{}
var tags = strings.Split(tag, ",")
for _, t := range tags {
switch strings.ToLower(t) {
case "yes":
res.Enabled = true
case "no":
res.Enabled = false
case "unique":
res.Unique = true
case "omitempty":
res.Omitempty = true
default:
index := strings.Index(t, ":")
if index != -1 {
keys = append(keys, t)
res.Attrs[t[:index]] = t[index+1:]
} else {
res.Name = t
}
}
}
res.Key = strings.Join(keys, ",")
return res
}
func mapDecode(from interface{}) (map[string]interface{}, error) {
// wont use mapstructure,
// just because it ignores 'omitempty' and such json tags
var m map[string]interface{}
b, err := json.Marshal(from)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &m)
return m, err
}
func strDecode(from interface{}, to interface{}) error {
var dc = ms.DecoderConfig{TagName: "json", Result: to}
var dec *ms.Decoder
dec, _ = ms.NewDecoder(&dc)
return dec.Decode(from)
}
func extractJsonTag(field reflect.StructField) string {
jstag := field.Tag.Get("json")
ind := strings.Index(jstag, ",")
if ind != -1 {
jstag = jstag[:ind]
}
return jstag
}
func MarshalInline(val interface{}) (b []byte, e error) {
m, err := mapDecode(val)
if err != nil {
return nil, err
}
var v = reflect.ValueOf(val)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return json.Marshal(m)
}
for i := 0; i < v.NumField(); i++ {
field := v.Type().Field(i)
tag := parseInlineTag(field.Tag.Get("inline"))
if tag.Enabled {
f, e := mapDecode(v.Field(i).Interface())
if e != nil {
return nil, e
}
if tag.Omitempty && len(f) == 0 {
continue
}
if tag.Unique {
if len(tag.Name) == 0 {
m[field.Name] = f
} else {
m[tag.Name] = f
}
} else {
for n, v := range f {
m[n] = v
}
}
}
}
return json.Marshal(m)
}
func UnmarshalInline(b []byte, val interface{}, tmpl map[string]interface{}) error {
var doc map[string]interface{}
var err error
if err = json.Unmarshal(b, &doc); err != nil {
return err
}
if doc == nil {
return nil
}
if err = json.Unmarshal(b, val); err != nil {
return err
}
// if 'val' is not a ptr, we'll be kicked out by json.Unmarshal
var v = reflect.ValueOf(val).Elem()
if v.Kind() != reflect.Struct {
return nil
}
// remove non-inline
var key_inlines = []int{}
var def_inlines = []int{}
for i := 0; i < v.NumField(); i++ {
field := v.Type().Field(i)
tag := parseInlineTag(field.Tag.Get("inline"))
if !tag.Enabled {
delete(doc, extractJsonTag(field))
} else if len(tag.Attrs) != 0 {
key_inlines = append(key_inlines, i)
} else {
def_inlines = append(def_inlines, i)
}
}
var none_attrs = deepcopy.Copy(doc).(map[string]interface{})
for _, i := range key_inlines {
field := v.Type().Field(i)
tag := parseInlineTag(field.Tag.Get("inline"))
var attrs = map[string]interface{}{}
for key, val := range doc {
vmap, ok := val.(map[string]interface{})
if !ok {
continue
}
ok = true
for check_key, check_val := range tag.Attrs {
value, has_value := vmap[check_key]
if !has_value || value != check_val {
ok = false
}
}
if !ok {
continue
}
delete(none_attrs, key)
if tag.Unique {
attrs = vmap
break
} else {
attrs[key] = val
}
}
var f = v.Field(i)
tmp, ok := tmpl[tag.Key]
if !ok {
return fmt.Errorf("no template for %s", tag.Key)
}
err = strDecode(attrs, tmp)
if err != nil {
return err
}
f.Set(reflect.ValueOf(tmp).Elem())
}
for _, i := range def_inlines {
var f = v.Field(i)
tmp, ok := tmpl[""]
if !ok {
return errors.New("no template for default key")
}
err = strDecode(none_attrs, tmp)
if err != nil {
return err
}
f.Set(reflect.ValueOf(tmp).Elem())
}
return nil
}