Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce config.FromEnv() #41

Merged
merged 14 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package config
import (
stderrors "errors"
"fmt"
"github.com/caarlos0/env/v11"
"github.com/creasty/defaults"
"github.com/goccy/go-yaml"
"github.com/jessevdk/go-flags"
Expand Down Expand Up @@ -50,6 +51,32 @@ func FromYAMLFile(name string, v Validator) error {
return nil
}

// EnvOptions is a type alias for [env.Options], so that only this package needs to import [env].
type EnvOptions = env.Options

// FromEnv parses environment variables and stores the result in the value pointed to by v.
// If v is nil or not a pointer, FromEnv returns an [ErrInvalidArgument] error.
func FromEnv(v Validator, options EnvOptions) error {
rv := reflect.ValueOf(v)
lippserd marked this conversation as resolved.
Show resolved Hide resolved
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return errors.Wrapf(ErrInvalidArgument, "non-nil pointer expected, got %T", v)
}

if err := defaults.Set(v); err != nil {
return errors.Wrap(err, "can't set config defaults")
}

if err := env.ParseWithOptions(v, options); err != nil {
return errors.Wrap(err, "can't parse environment variables")
}

if err := v.Validate(); err != nil {
return errors.Wrap(err, "invalid configuration")
}

return nil
}

// ParseFlags parses CLI flags and stores the result
// in the value pointed to by v. If v is nil or not a pointer,
// ParseFlags returns an [ErrInvalidArgument] error.
Expand Down
Loading
Loading