-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv_source.go
More file actions
59 lines (47 loc) · 1.04 KB
/
Copy pathenv_source.go
File metadata and controls
59 lines (47 loc) · 1.04 KB
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
package confkit
import (
"context"
"os"
"strings"
)
func FromEnv() Source {
return &envSource{}
}
type envSource struct{}
func (e *envSource) Name() string {
return "env"
}
func (e *envSource) Lookup(_ context.Context, field *FieldInfo) (any, bool, error) {
envName := field.Tags["env"]
if envName == "" {
return "", false, nil
}
prefix := buildEnvPrefix(field.AncestorTags)
if p := field.Tags["prefix"]; p != "" {
prefix += p
}
fullName := prefix + envName
value, ok := os.LookupEnv(fullName)
return value, ok, nil
}
func buildEnvPrefix(ancestorTags []map[string]string) string {
var prefixes []string
for _, tags := range ancestorTags {
if p := tags["prefix"]; p != "" {
prefixes = append(prefixes, p)
}
}
return strings.Join(prefixes, "")
}
type errorSource struct {
err error
}
func (e *errorSource) Name() string {
return "error"
}
func (e *errorSource) Lookup(_ context.Context, _ *FieldInfo) (any, bool, error) {
return "", false, e.err
}
func NewErrorSource(err error) Source {
return &errorSource{err: err}
}