-
Notifications
You must be signed in to change notification settings - Fork 2
/
json.go
326 lines (263 loc) · 6.05 KB
/
json.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package jsonparser
import (
"bytes"
"encoding/json"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"unicode/utf8"
)
const (
optRequired = "required"
optNotEmpty = "notEmpty"
optNotNull = "notNull"
optUniq = "uniq"
optMin = "min:"
optMax = "max:"
)
type fieldOpt struct {
required bool
notEmpty bool
notNull bool
uniq bool
min *int
max *int
}
type validError struct {
path string
reason string
}
// Error returns error text
func (e validError) Error() string {
return fmt.Sprintf("value [%s] %s", e.path, e.reason)
}
func newError(reason string, path ...string) error {
return validError{
path: strings.Join(path, ""),
reason: reason,
}
}
func parseTag(data string) (string, fieldOpt) {
values := strings.Split(data, ",")
opt := fieldOpt{}
for _, o := range values[1:] {
switch o {
case optRequired:
opt.required = true
case optNotEmpty:
opt.notEmpty = true
case optNotNull:
opt.notNull = true
case optUniq:
opt.uniq = true
}
if strings.HasPrefix(o, optMin) {
if v, err := strconv.Atoi(o[4:]); err == nil {
opt.min = &v
}
continue
}
if strings.HasPrefix(o, optMax) {
if v, err := strconv.Atoi(o[4:]); err == nil {
opt.max = &v
}
continue
}
}
return values[0], opt
}
func fieldIs(t reflect.Type, kind reflect.Kind) bool {
for {
if t.Kind() == reflect.Ptr {
t = t.Elem()
continue
}
if t.Kind() == kind {
return true
}
return false
}
}
func valueIsZero(v reflect.Value) bool {
for {
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return false
}
v = v.Elem()
continue
}
return v.IsZero()
}
}
func validateMinMax(opt fieldOpt, prefix string, v int, errorPrefix string) error {
if opt.min != nil && v < *opt.min {
return newError(fmt.Sprintf("%s less than expected", errorPrefix), prefix)
}
if opt.max != nil && v > *opt.max {
return newError(fmt.Sprintf("%s more than expected", errorPrefix), prefix)
}
return nil
}
func getString(v reflect.Value) (string, bool) {
for {
if v.Kind() == reflect.Ptr {
v = v.Elem()
continue
}
if v.Kind() != reflect.String {
return "", false
}
return v.String(), true
}
}
func getInt(v reflect.Value) (int64, bool) {
for {
if v.Kind() == reflect.Ptr {
v = v.Elem()
continue
}
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int(), true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return (int64)(v.Uint()), true
default:
return 0, false
}
}
}
func parseJsonObject(r io.Reader, prefix string, val reflect.Value) error {
data := map[string]json.RawMessage{}
err := json.NewDecoder(r).Decode(&data)
if err != nil {
return err
}
for {
if val.Kind() == reflect.Ptr {
if val.Elem().Kind() == reflect.Invalid {
newVal := reflect.New(val.Type().Elem())
val.Set(newVal)
val = newVal
}
val = val.Elem()
} else {
break
}
}
for i := 0; i < val.NumField(); i++ {
tag := val.Type().Field(i).Tag.Get("json")
var (
name string
opts fieldOpt
)
if len(tag) == 0 {
name = val.Type().Field(i).Name
} else {
name, opts = parseTag(tag)
}
jsonValue, valueExist := data[name]
if !valueExist {
if opts.required {
return newError("is required", prefix, name)
}
continue
}
if opts.notNull && string(jsonValue) == "null" {
return newError("must be not null", prefix, name)
}
refField := val.Field(i)
err := parseJson(bytes.NewReader(jsonValue), fmt.Sprintf("%s%s.", prefix, name), opts, refField.Addr())
if err != nil {
return err
}
if opts.notEmpty && valueIsZero(refField) && string(jsonValue) != "null" {
return newError("must be not empty", prefix, name)
}
}
return nil
}
func parseJsonSlice(r io.Reader, prefix string, opt fieldOpt, val reflect.Value) error {
var data []json.RawMessage
err := json.NewDecoder(r).Decode(&data)
if err != nil {
return err
}
err = validateMinMax(opt, prefix, len(data), "count of items")
if err != nil {
return err
}
for {
if val.Kind() != reflect.Ptr {
break
}
val = val.Elem()
}
if opt.uniq {
if val.Type().Elem().Kind() == reflect.String {
for i, v := range data {
for j := i + 1; j < len(data); j++ {
if bytes.Compare(v, data[j]) == 0 {
return newError("contains repeated values", prefix)
}
}
}
}
}
for i, d := range data {
newVal := reflect.New(val.Type().Elem())
val.Set(reflect.Append(val, newVal.Elem()))
err := parseJson(bytes.NewReader(d), fmt.Sprintf("%s[%d].", prefix, i), opt, val.Index(i).Addr())
if err != nil {
return err
}
}
return nil
}
func parseJsonValue(r io.Reader, prefix string, opt fieldOpt, val reflect.Value) error {
tempVal := reflect.New(val.Type().Elem())
err := json.NewDecoder(r).Decode(tempVal.Interface())
if err != nil {
return newError(err.Error(), prefix)
}
if str, ok := getString(tempVal); ok {
err := validateMinMax(opt, prefix, utf8.RuneCountInString(str), "count of runes in a string")
if err != nil {
return err
}
} else if i, ok := getInt(tempVal); ok {
err := validateMinMax(opt, prefix, (int)(i), "value")
if err != nil {
return err
}
}
val.Elem().Set(tempVal.Elem())
return nil
}
func parseJson(r io.Reader, prefix string, opt fieldOpt, val reflect.Value) error {
if fieldIs(val.Type(), reflect.Struct) {
return parseJsonObject(r, prefix, val)
}
if fieldIs(val.Type(), reflect.Slice) {
return parseJsonSlice(r, prefix, opt, val)
}
return parseJsonValue(r, prefix, opt, val)
}
// Decoder is a struct for parsing and validation JSON
type Decoder struct {
r io.Reader
}
// NewDecoder created and return new decoder
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{r: r}
}
// Decode run parsing and validation JSON from reader
func (dec *Decoder) Decode(v interface{}) error {
return parseJson(dec.r, "", fieldOpt{}, reflect.ValueOf(v))
}
// Unmarshal run parsing and validation JSON using default decoder
func Unmarshal(data []byte, v interface{}) error {
return NewDecoder(bytes.NewBuffer(data)).Decode(v)
}