@@ -3,6 +3,7 @@ package config
3
3
import (
4
4
stderrors "errors"
5
5
"fmt"
6
+ "github.com/caarlos0/env/v11"
6
7
"github.com/creasty/defaults"
7
8
"github.com/goccy/go-yaml"
8
9
"github.com/jessevdk/go-flags"
@@ -50,6 +51,32 @@ func FromYAMLFile(name string, v Validator) error {
50
51
return nil
51
52
}
52
53
54
+ // EnvOptions is a type alias for [env.Options], so that only this package needs to import [env].
55
+ type EnvOptions = env.Options
56
+
57
+ // FromEnv parses environment variables and stores the result in the value pointed to by v.
58
+ // If v is nil or not a pointer, FromEnv returns an [ErrInvalidArgument] error.
59
+ func FromEnv (v Validator , options EnvOptions ) error {
60
+ rv := reflect .ValueOf (v )
61
+ if rv .Kind () != reflect .Ptr || rv .IsNil () {
62
+ return errors .Wrapf (ErrInvalidArgument , "non-nil pointer expected, got %T" , v )
63
+ }
64
+
65
+ if err := defaults .Set (v ); err != nil {
66
+ return errors .Wrap (err , "can't set config defaults" )
67
+ }
68
+
69
+ if err := env .ParseWithOptions (v , options ); err != nil {
70
+ return errors .Wrap (err , "can't parse environment variables" )
71
+ }
72
+
73
+ if err := v .Validate (); err != nil {
74
+ return errors .Wrap (err , "invalid configuration" )
75
+ }
76
+
77
+ return nil
78
+ }
79
+
53
80
// ParseFlags parses CLI flags and stores the result
54
81
// in the value pointed to by v. If v is nil or not a pointer,
55
82
// ParseFlags returns an [ErrInvalidArgument] error.
0 commit comments