/
structconfig.go
58 lines (51 loc) · 1.41 KB
/
structconfig.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
package structconfig
import (
"encoding/json"
"fmt"
"strings"
"github.com/artnez/structconfig/v2/internal"
)
type Field struct {
Name string
Value interface{}
Tag string
}
func FromEnviron(config interface{}, environ []string) {
fields := internal.NewFields(config, true)
tags := fields.Tags("env")
values := internal.NewEnviron(environ)
update := map[string]interface{}{}
for _, field := range fields {
if tag, ok := tags[field.Name]; ok {
if value, ok := values[tag.Name]; ok {
update[field.Name] = value
}
}
}
internal.Decode(update, config)
}
func Slice(config interface{}, withSecrets bool) []Field {
fields := internal.NewFields(config, withSecrets)
result := []Field{}
for _, field := range fields {
result = append(result, Field{field.Name, field.Value.Interface(), field.Tag.Get("env")})
}
return result
}
func Map(config interface{}, withSecrets bool) map[string]interface{} {
fields := internal.NewFields(config, withSecrets)
result := map[string]interface{}{}
for _, field := range fields {
result[field.Name] = field.Value.Interface()
}
return result
}
func String(config interface{}, withSecrets bool) string {
fields := internal.NewFields(config, withSecrets)
buffer := []string{}
for _, field := range fields {
value, _ := json.Marshal(field.Value.Interface())
buffer = append(buffer, fmt.Sprintf("%s=%s", field.Name, value))
}
return strings.Join(buffer, ", ")
}