-
Notifications
You must be signed in to change notification settings - Fork 2
/
required.go
78 lines (68 loc) · 1.47 KB
/
required.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
package lib
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/fatih/structs"
)
func CheckRequired(iStruct interface{}) error {
var errors = make([]string, 0)
val := reflect.ValueOf(iStruct)
for val.Kind() == reflect.Ptr {
if val.IsNil() {
return nil
}
val = val.Elem()
}
if iStruct == nil {
return nil
}
if val.Kind() == reflect.Map {
return nil
}
if val.Kind() != reflect.Struct {
return fmt.Errorf("CheckRequired expects struct input. Got %v", val.Kind())
}
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
sf := typ.Field(i)
if sf.PkgPath != "" && !sf.Anonymous { // unexported
continue
}
tag := sf.Tag.Get("required")
m := structs.Map(iStruct)
jsonValue, err := json.Marshal(m[sf.Name])
if err != nil {
return err
}
if tag == "true" && (string(jsonValue) == "null" || string(jsonValue) == JSONEmptyValue(sf.Type)) {
errors = append(
errors,
CreateError(iStruct, sf.Name).Error(),
)
}
}
if len(errors) != 0 {
return fmt.Errorf(strings.Join(errors, "\n"))
}
return nil
}
func CreateError(i interface{}, name string) error {
structName := reflect.TypeOf(i).Name()
return fmt.Errorf("missing required field: %v{}.%v", structName, name)
}
func JSONEmptyValue(v reflect.Type) string {
switch v.Kind() {
case reflect.Map, reflect.Struct:
return "{}"
case reflect.Slice:
return "[]"
case reflect.Int, reflect.Int64:
return "0"
case reflect.String:
return `""`
default:
return ""
}
}