-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathenvProvider.go
48 lines (38 loc) · 949 Bytes
/
envProvider.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
package configuration
import (
"fmt"
"os"
"reflect"
"strings"
)
const (
EnvProviderName = `EnvProvider`
EnvProviderTag = `env`
)
// NewEnvProvider creates provider which sets values from ENV variables (gets variable name from `env` tag)
// nolint:revive
func NewEnvProvider() envProvider {
return envProvider{}
}
type envProvider struct{}
func (envProvider) Name() string {
return EnvProviderName
}
func (envProvider) Tag() string {
return EnvProviderTag
}
func (envProvider) Init(_ any) error {
return nil
}
func (ep envProvider) Provide(field reflect.StructField, v reflect.Value) error {
key := field.Tag.Get(EnvProviderTag)
if len(key) == 0 {
// field doesn't have a proper tag
return fmt.Errorf("%s: key is empty", EnvProviderName)
}
valStr, ok := os.LookupEnv(strings.ToUpper(key))
if !ok || len(valStr) == 0 {
return fmt.Errorf("%s: %w", EnvProviderName, ErrEmptyValue)
}
return SetField(field, v, valStr)
}