-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator_struct_update.go
395 lines (365 loc) · 14 KB
/
validator_struct_update.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package validator
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"slices"
"strings"
"github.com/siherrmann/validator/helper"
"github.com/siherrmann/validator/model"
"github.com/siherrmann/validator/validators"
)
// UnmapOrAnmarshalValidateAndUpdate unmarshals given json ([]byte) or given url.Values (from request.Form),
// validates them and updates the given struct.
func UnmapOrUnmarshalRequestValidateAndUpdate(request *http.Request, structToUpdate interface{}) error {
err := request.ParseForm()
if err != nil {
return err
}
if len(request.Form.Encode()) > 0 {
err = UnmapValidateAndUpdate(request.Form, structToUpdate)
} else {
var bodyBytes []byte
bodyBytes, err = io.ReadAll(request.Body)
if err != nil {
return err
}
err = UnmarshalValidateAndUpdate(bodyBytes, structToUpdate)
}
return err
}
// UnmarshalValidateAndUpdate unmarshals given json ([]byte) into pointer v.
// For more information to ValidateAndUpdate look at ValidateAndUpdate(jsonInput model.JsonMap, structToUpdate interface{}) error.
func UnmarshalValidateAndUpdate(jsonInput []byte, structToUpdate interface{}) error {
jsonUnmarshaled := model.JsonMap{}
err := json.Unmarshal(jsonInput, &jsonUnmarshaled)
if err != nil {
return fmt.Errorf("error unmarshaling: %v", err)
}
err = ValidateAndUpdate(jsonUnmarshaled, structToUpdate)
if err != nil {
return fmt.Errorf("error updating struct: %v", err)
}
return nil
}
// UnmapValidateAndUpdate unmaps given url.Values into pointer jsonMap.
// For more information to ValidateAndUpdate look at ValidateAndUpdate(jsonInput model.JsonMap, structToUpdate interface{}) error.
func UnmapValidateAndUpdate(values url.Values, structToUpdate interface{}) error {
mapOut, err := UnmapUrlValuesToJsonMap(values)
if err != nil {
return err
}
err = ValidateAndUpdate(mapOut, structToUpdate)
if err != nil {
return fmt.Errorf("error updating struct: %v", err)
}
return nil
}
// ValidateAndUpdate validates a given struct by upd tags.
// ValidateAndUpdate needs a struct pointer and a json map as input.
// The given struct is updated by the values in the json map.
//
// All fields in the struct need a upd tag.
// The tag has to contain the key value for the json struct.
// If no tag is present the field in the struct is ignored and does not get updated.
//
// The second part of the tag contains the conditions for the validation.
//
// If you want to use multiple conditions you can add them with a space in between them.
//
// A complex example for password would be:
// `upd:"password, min8 max30 rex^(.*[A-Z])+(.*)$ rex^(.*[a-z])+(.*)$ rex^(.*\\d)+(.*)$ rex^(.*[\x60!@#$%^&*()_+={};':\"|\\,.<>/?~-])+(.*)$"`
//
// If you want don't want to validate the field you can add `upd:"json_key, -"`.
// If you don't add the upd tag to every field the function will fail with an error.
//
// Conditions have different usages per variable type:
//
// equ - int/float/string == condition, len(array) == condition
//
// neq - int/float/string != condition, len(array) != condition
//
// min - int/float >= condition, len(string/array) >= condition
//
// max - int/float <= condition, len(string/array) <= condition
//
// con - strings.Contains(string, condition), contains(array, condition), int/float ignored
//
// rex - regexp.MatchString(condition, int/float/string), array ignored
//
// For con you need to put in a condition that is convertable to the underlying type of the arrary.
// Eg. for an array of int the condition must be convertable to int (bad: `upd:"array, conA"`, good: `upd:"array, con1"`).
//
// In the case of rex the int and float input will get converted to a string (strconv.Itoa(int) and fmt.Sprintf("%f", f)).
// If you want to check more complex cases you can obviously replace equ, neq, min, max and con with one regular expression.
func ValidateAndUpdate(jsonInput model.JsonMap, structToUpdate interface{}) error {
// check if value is a pointer to a struct
value := reflect.ValueOf(structToUpdate)
if value.Kind() != reflect.Ptr {
return fmt.Errorf("value has to be of kind pointer, was %T", value)
}
if value.Elem().Kind() != reflect.Struct {
return fmt.Errorf("value has to be of kind struct, was %T", value)
}
// get valid reflect value of struct
structFull := value.Elem()
keys := []string{}
groups := map[string]*model.Group{}
groupSize := map[string]int{}
groupErrors := map[string][]error{}
for i := 0; i < structFull.Type().NumField(); i++ {
tag := structFull.Type().Field(i).Tag.Get(string(model.UPD))
field := structFull.Field(i)
fieldName := structFull.Type().Field(i).Name
validation := &model.Validation{}
err := validation.Fill(tag, model.UPD, field)
if err != nil {
return err
}
if len(validation.Key) > 0 && slices.Contains(keys, validation.Key) {
return fmt.Errorf("duplicate validation key: %v", validation.Key)
} else {
keys = append(keys, validation.Key)
}
for _, g := range validation.Groups {
groups[g.Name] = g
groupSize[g.Name]++
}
var ok bool
var jsonValue interface{}
if jsonValue, ok = jsonInput[validation.Key]; !ok {
if strings.TrimSpace(validation.Requirement) == string(model.NONE) {
continue
} else if len(validation.Groups) == 0 {
return fmt.Errorf("json %v key not in map", validation.Key)
} else {
for _, group := range validation.Groups {
groupErrors[group.Name] = append(groupErrors[group.Name], fmt.Errorf("json %v key not in map", validation.Key))
}
continue
}
}
var validatedValue interface{}
if validation.Type == model.Struct {
var validMap interface{}
validMap, err = validation.GetValidValue(jsonValue)
if err != nil {
return err
}
err = ValidateAndUpdate(validMap.(map[string]interface{}), field.Addr().Interface())
validatedValue = field.Interface()
} else {
validatedValue, err = ValidateValueWithParser(reflect.ValueOf(jsonValue), validation)
}
if err != nil && len(validation.Groups) == 0 {
return fmt.Errorf("field %v of %v invalid: %v", fieldName, reflect.TypeOf(structToUpdate), err.Error())
} else if err != nil {
for _, group := range validation.Groups {
groupErrors[group.Name] = append(groupErrors[group.Name], fmt.Errorf("field %v of %v invalid: %v", fieldName, reflect.TypeOf(structToUpdate), err.Error()))
}
continue
}
err = setStructValueByJson(field, validation.Key, validatedValue)
if err != nil && len(validation.Groups) == 0 {
return fmt.Errorf("could not set field %v of %v: %v", fieldName, reflect.TypeOf(structToUpdate), err.Error())
} else if err != nil {
for _, group := range groups {
groupErrors[group.Name] = append(groupErrors[group.Name], fmt.Errorf("could not set field %v: %v", fieldName, err.Error()))
}
continue
}
}
err := validators.ValidateGroups(groups, groupSize, groupErrors)
if err != nil {
return err
}
return nil
}
func setStructValueByJson(fv reflect.Value, jsonKey string, jsonValue interface{}) error {
if fv.IsValid() && fv.CanSet() {
switch fv.Kind() {
case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8:
var newInt int64
if fl, ok := jsonValue.(float64); ok {
// This case is for the case that json.Unmarshal unmarshals an int value into a float64 value.
newInt = int64(fl)
} else if _, ok := jsonValue.(int); ok {
newInt = int64(jsonValue.(int))
} else if _, ok := jsonValue.(int64); ok {
newInt = int64(jsonValue.(int64))
} else if _, ok := jsonValue.(int32); ok {
newInt = int64(jsonValue.(int32))
} else if _, ok := jsonValue.(int16); ok {
newInt = int64(jsonValue.(int16))
} else if _, ok := jsonValue.(int8); ok {
newInt = int64(jsonValue.(int8))
} else {
return fmt.Errorf("input value has to be of type %v, was %v", fv.Kind(), reflect.ValueOf(jsonValue).Kind())
}
if fv.OverflowInt(newInt) {
return fmt.Errorf("cannot set overflowing int for field %v", jsonKey)
}
fv.SetInt(newInt)
case reflect.Float64, reflect.Float32:
var newFloat float64
if fl, ok := jsonValue.(float64); ok {
newFloat = float64(fl)
} else if fl, ok := jsonValue.(float32); ok {
newFloat = float64(fl)
} else {
return fmt.Errorf("input value has to be of type %v, was %v", fv.Kind(), reflect.ValueOf(jsonValue).Kind())
}
if fv.OverflowFloat(newFloat) {
return fmt.Errorf("cannot set overflowing float for field %v", jsonKey)
}
fv.SetFloat(newFloat)
case reflect.String:
if _, ok := jsonValue.(string); !ok {
return fmt.Errorf("input value has to be of type %v, was %v", fv.Kind(), reflect.ValueOf(jsonValue).Kind())
}
fv.SetString(string(jsonValue.(string)))
case reflect.Bool:
if _, ok := jsonValue.(bool); !ok {
return fmt.Errorf("input value has to be of type %v, was %v", fv.Kind(), reflect.ValueOf(jsonValue).Kind())
}
fv.SetBool(bool(jsonValue.(bool)))
case reflect.Struct:
if v, ok := jsonValue.(string); ok {
date, err := model.InterfaceFromString(v, model.Time)
if err != nil {
return err
}
fv.Set(reflect.ValueOf(date))
} else {
fv.Set(reflect.ValueOf(jsonValue))
}
case reflect.Map:
if _, ok := jsonValue.(map[string]interface{}); !ok {
return fmt.Errorf("input value has to be of type %v, was %v", fv.Kind(), reflect.ValueOf(jsonValue).Kind())
}
fv.Set(reflect.ValueOf(jsonValue))
case reflect.Array, reflect.Slice:
if reflect.TypeOf(jsonValue).Kind() != reflect.Array && reflect.TypeOf(jsonValue).Kind() != reflect.Slice {
return fmt.Errorf("input value has to be of type %v or %v, was %v of %v", reflect.Array, reflect.Slice, reflect.ValueOf(jsonValue).Kind(), reflect.TypeOf(jsonValue).Elem().Kind())
}
switch t := reflect.TypeOf(fv.Interface()).Elem().Kind(); t {
case reflect.Int:
if _, ok := jsonValue.([]interface{}); ok {
typedArray, err := helper.ArrayOfInterfaceToArrayOf[int](jsonValue.([]interface{}))
if err != nil {
return err
}
fv.Set(reflect.ValueOf(typedArray))
} else if _, ok := jsonValue.([]int); ok {
fv.Set(reflect.ValueOf(jsonValue.([]int)))
} else {
return fmt.Errorf("input value has to be of type %v, was %v", t, reflect.TypeOf(jsonValue).Elem().Kind())
}
case reflect.Int64:
if _, ok := jsonValue.([]interface{}); ok {
typedArray, err := helper.ArrayOfInterfaceToArrayOf[int64](jsonValue.([]interface{}))
if err != nil {
return err
}
fv.Set(reflect.ValueOf(typedArray))
} else if _, ok := jsonValue.([]int64); ok {
fv.Set(reflect.ValueOf(jsonValue.([]int64)))
} else {
return fmt.Errorf("input value has to be of type %v, was %v", t, reflect.TypeOf(jsonValue).Elem().Kind())
}
case reflect.Int32:
if _, ok := jsonValue.([]interface{}); ok {
typedArray, err := helper.ArrayOfInterfaceToArrayOf[int32](jsonValue.([]interface{}))
if err != nil {
return err
}
fv.Set(reflect.ValueOf(typedArray))
} else if _, ok := jsonValue.([]int32); ok {
fv.Set(reflect.ValueOf(jsonValue.([]int32)))
} else {
return fmt.Errorf("input value has to be of type %v, was %v", t, reflect.TypeOf(jsonValue).Elem().Kind())
}
case reflect.Int16:
if _, ok := jsonValue.([]interface{}); ok {
typedArray, err := helper.ArrayOfInterfaceToArrayOf[int16](jsonValue.([]interface{}))
if err != nil {
return err
}
fv.Set(reflect.ValueOf(typedArray))
} else if _, ok := jsonValue.([]int16); ok {
fv.Set(reflect.ValueOf(jsonValue.([]int16)))
} else {
return fmt.Errorf("input value has to be of type %v, was %v", t, reflect.TypeOf(jsonValue).Elem().Kind())
}
case reflect.Int8:
if _, ok := jsonValue.([]interface{}); ok {
typedArray, err := helper.ArrayOfInterfaceToArrayOf[int8](jsonValue.([]interface{}))
if err != nil {
return err
}
fv.Set(reflect.ValueOf(typedArray))
} else if _, ok := jsonValue.([]int8); ok {
fv.Set(reflect.ValueOf(jsonValue.([]int8)))
} else {
return fmt.Errorf("input value has to be of type %v, was %v", t, reflect.TypeOf(jsonValue).Elem().Kind())
}
case reflect.Float64:
if _, ok := jsonValue.([]interface{}); ok {
typedArray, err := helper.ArrayOfInterfaceToArrayOf[float64](jsonValue.([]interface{}))
if err != nil {
return err
}
fv.Set(reflect.ValueOf(typedArray))
} else if _, ok := jsonValue.([]float64); ok {
fv.Set(reflect.ValueOf(jsonValue.([]float64)))
} else {
return fmt.Errorf("input value has to be of type %v, was %v", t, reflect.TypeOf(jsonValue).Elem().Kind())
}
case reflect.Float32:
if _, ok := jsonValue.([]interface{}); ok {
typedArray, err := helper.ArrayOfInterfaceToArrayOf[float32](jsonValue.([]interface{}))
if err != nil {
return err
}
fv.Set(reflect.ValueOf(typedArray))
} else if _, ok := jsonValue.([]float32); ok {
fv.Set(reflect.ValueOf(jsonValue.([]float32)))
} else {
return fmt.Errorf("input value has to be of type %v, was %v", t, reflect.TypeOf(jsonValue).Elem().Kind())
}
case reflect.String:
if _, ok := jsonValue.([]interface{}); ok {
typedArray, err := helper.ArrayOfInterfaceToArrayOf[string](jsonValue.([]interface{}))
if err != nil {
return err
}
fv.Set(reflect.ValueOf(typedArray))
} else if _, ok := jsonValue.([]string); ok {
fv.Set(reflect.ValueOf(jsonValue.([]string)))
} else {
return fmt.Errorf("input value has to be of type %v, was %v", t, reflect.TypeOf(jsonValue).Elem().Kind())
}
case reflect.Bool:
if _, ok := jsonValue.([]interface{}); ok {
typedArray, err := helper.ArrayOfInterfaceToArrayOf[bool](jsonValue.([]interface{}))
if err != nil {
return err
}
fv.Set(reflect.ValueOf(typedArray))
} else if _, ok := jsonValue.([]bool); ok {
fv.Set(reflect.ValueOf(jsonValue.([]bool)))
} else {
return fmt.Errorf("input value has to be of type %v, was %v", t, reflect.TypeOf(jsonValue).Elem().Kind())
}
default:
return fmt.Errorf("invalid array element type: %v", reflect.TypeOf(fv.Interface()).Elem().Kind())
}
default:
return fmt.Errorf("invalid field type of %v: %v", jsonKey, reflect.TypeOf(jsonValue).Elem().Kind())
}
}
return nil
}