-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.go
52 lines (45 loc) · 904 Bytes
/
env.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
package confcrypt
import (
"fmt"
"os"
"reflect"
)
func DecodeInplace(v interface{}, key string) error {
decoded, err := Decode(v, key)
if err != nil {
return err
}
if reflect.TypeOf(v).Kind() == reflect.Ptr {
reflect.ValueOf(v).Elem().Set(reflect.ValueOf(decoded).Elem())
return nil
}
reflect.ValueOf(v).Set(reflect.ValueOf(decoded))
return nil
}
func DecodeByEnv(v interface{}, opts ...DecodeOption) error {
o := defaultOption
for _, opt := range opts {
opt(&o)
}
key := os.Getenv(o.env)
if key == "" {
err := DecodeInplace(v, key)
if err != nil {
return fmt.Errorf("empty key: %w", err)
}
return nil
}
return DecodeInplace(v, key)
}
var defaultOption = decodeOption{
env: "CONFIG_KEY",
}
type decodeOption struct {
env string
}
type DecodeOption func(*decodeOption)
func WithEnv(env string) DecodeOption {
return func(o *decodeOption) {
o.env = env
}
}