-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoenv.go
43 lines (37 loc) · 1016 Bytes
/
goenv.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
// Package goenv provides a simple way to populate the fields of a struct with
// the values of the environment variables.
package goenv
import (
"errors"
"os"
"reflect"
"github.com/ggicci/owl"
)
var (
ErrMissingName = errors.New("missing name of the environment variable")
ErrInvalidType = errors.New("only string field can be tagged with env")
)
func nameDirective(rtm *owl.DirectiveRuntime) error {
if len(rtm.Directive.Argv) == 0 {
return ErrMissingName
}
if value, ok := os.LookupEnv(rtm.Directive.Argv[0]); ok {
if rtm.Value.Elem().Type().Kind() != reflect.String {
return ErrInvalidType
}
rtm.Value.Elem().SetString(value)
}
return nil
}
func init() {
owl.UseTag("env")
owl.RegisterDirectiveExecutor("name", owl.DirectiveExecutorFunc(nameDirective))
}
// Load populates the fields of the value with the values of the environment variables.
func Load(value interface{}) error {
resolver, err := owl.New(value)
if err != nil {
return err
}
return resolver.ResolveTo(value)
}