Skip to content

Commit 4c2f63f

Browse files
authored
Merge pull request #41 from Icinga/FromEnv
Introduce config.FromEnv()
2 parents 38f518b + f1bb16e commit 4c2f63f

13 files changed

+1015
-143
lines changed

config/config.go

+27
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package config
33
import (
44
stderrors "errors"
55
"fmt"
6+
"github.com/caarlos0/env/v11"
67
"github.com/creasty/defaults"
78
"github.com/goccy/go-yaml"
89
"github.com/jessevdk/go-flags"
@@ -50,6 +51,32 @@ func FromYAMLFile(name string, v Validator) error {
5051
return nil
5152
}
5253

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+
5380
// ParseFlags parses CLI flags and stores the result
5481
// in the value pointed to by v. If v is nil or not a pointer,
5582
// ParseFlags returns an [ErrInvalidArgument] error.

0 commit comments

Comments
 (0)