-
Notifications
You must be signed in to change notification settings - Fork 0
/
structProtoContext.go
79 lines (64 loc) · 1.72 KB
/
structProtoContext.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
package structproto
import "reflect"
type StructProtoContext Struct
func (ctx *StructProtoContext) Target() reflect.Value {
return ctx.target
}
func (ctx *StructProtoContext) FieldInfo(name string) FieldInfo {
return ctx.getFieldInfoImpl(name)
}
func (ctx *StructProtoContext) Field(name string) (v reflect.Value, ok bool) {
info := ctx.FieldInfo(name)
if info != nil {
return ctx.target.Field(info.Index()), true
}
return reflect.Value{}, false
}
func (ctx *StructProtoContext) FieldNames() []string {
var fields []string = make([]string, len(ctx.fields))
for _, v := range ctx.fields {
fields[v.index] = v.name
}
return fields
}
func (ctx *StructProtoContext) RequiredFields() []string {
return ctx.requiredFields
}
func (ctx *StructProtoContext) IsRequired(name string) bool {
field := ctx.getFieldInfoImpl(name)
if field != nil {
return field.HasFlag(RequiredFlag)
}
return false
}
func (ctx *StructProtoContext) CheckIfMissingRequiredFields(visitFieldProc func() <-chan string) error {
if ctx.requiredFields.isEmpty() {
return nil
}
var requiredFields = ctx.requiredFields.clone()
for field := range visitFieldProc() {
index := requiredFields.indexOf(field)
if index != -1 {
requiredFields.removeIndex(index)
}
// break loop if no more required fields
if requiredFields.isEmpty() {
return nil
}
}
if !requiredFields.isEmpty() {
field, _ := requiredFields.get(0)
return &MissingRequiredFieldError{field, nil}
}
return nil
}
func (ctx *StructProtoContext) getFieldInfoImpl(name string) *FieldInfoImpl {
if field, ok := ctx.fields[name]; ok {
return field
}
return nil
}
func buildStructProtoContext(s *Struct) *StructProtoContext {
context := StructProtoContext(*s)
return &context
}