-
Notifications
You must be signed in to change notification settings - Fork 19
/
required.go
68 lines (57 loc) · 1.64 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
package jwt
import (
"errors"
"fmt"
"reflect"
"strings"
)
// ErrMissingKey when token does not contain a required JSON field.
// Check with errors.Is.
var ErrMissingKey = errors.New("jwt: token is missing a required field")
// HasRequiredJSONTag reports whether a specific value of "i"
// contains one or more `json:"xxx,required"` struct fields tags.
//
// Can be used to precalculate the unmarshaller (see `UnmarshalWithRequired`) too.
func HasRequiredJSONTag(field reflect.StructField) bool {
if isExported := field.PkgPath == ""; !isExported {
return false
}
tag := field.Tag.Get("json")
return strings.Contains(tag, ",required")
}
func meetRequirements(val reflect.Value) (err error) { // see `UnmarshalWithRequired`.
val = reflect.Indirect(val)
if val.Kind() != reflect.Struct {
return nil
}
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
// skip unexported fields here.
if isExported := field.PkgPath == ""; !isExported {
continue
}
if fieldTyp := indirectType(field.Type); fieldTyp.Kind() == reflect.Struct {
if err = meetRequirements(val.Field(i)); err != nil {
return err
}
continue
}
if HasRequiredJSONTag(field) {
if val.Field(i).IsZero() {
return fmt.Errorf("%w: %q", ErrMissingKey, field.Name)
}
}
}
return
}
// indirectType returns the value of a pointer-type "typ".
// If "typ" is a pointer, array, chan, map or slice it returns its Elem,
// otherwise returns the typ as it's.
func indirectType(typ reflect.Type) reflect.Type {
switch typ.Kind() {
case reflect.Ptr, reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
return typ.Elem()
}
return typ
}