-
Notifications
You must be signed in to change notification settings - Fork 64
/
tag.go
60 lines (50 loc) · 1.3 KB
/
tag.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
package multiconfig
import (
"reflect"
"github.com/fatih/structs"
)
// TagLoader satisfies the loader interface. It parses a struct's field tags
// and populates the each field with that given tag.
type TagLoader struct {
// DefaultTagName is the default tag name for struct fields to define
// default values for a field. Example:
//
// // Field's default value is "koding".
// Name string `default:"koding"`
//
// The default value is "default" if it's not set explicitly.
DefaultTagName string
}
func (t *TagLoader) Load(s interface{}) error {
if t.DefaultTagName == "" {
t.DefaultTagName = "default"
}
for _, field := range structs.Fields(s) {
if err := t.processField(t.DefaultTagName, field); err != nil {
return err
}
}
return nil
}
// processField gets tagName and the field, recursively checks if the field has the given
// tag, if yes, sets it otherwise ignores
func (t *TagLoader) processField(tagName string, field *structs.Field) error {
switch field.Kind() {
case reflect.Struct:
for _, f := range field.Fields() {
if err := t.processField(tagName, f); err != nil {
return err
}
}
default:
defaultVal := field.Tag(t.DefaultTagName)
if defaultVal == "" {
return nil
}
err := fieldSet(field, defaultVal)
if err != nil {
return err
}
}
return nil
}