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

chore: allow to use custom environment #214

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
50 changes: 33 additions & 17 deletions providers/env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import (

// Env implements an environment variables provider.
type Env struct {
prefix string
delim string
cb func(key string, value string) (string, interface{})
prefix string
delim string
environFunc func() []string
cb func(key string, value string) (string, interface{})
}

// Provider returns an environment variables provider that returns
Expand All @@ -31,28 +32,43 @@ type Env struct {
// If the callback returns an empty string, the variable will be
// ignored.
func Provider(prefix, delim string, cb func(s string) string) *Env {
e := &Env{
prefix: prefix,
delim: delim,
}
if cb != nil {
e.cb = func(key string, value string) (string, interface{}) {
return ProviderWithOptions(
WithPrefix(prefix),
WithDelimiter(delim),
WithCallback(func(key string, value string) (string, interface{}) {
return cb(key), value
}
}
return e
}),
)
}

// ProviderWithValue works exactly the same as Provider except the callback
// takes a (key, value) with the variable name and value and allows you
// to modify both. This is useful for cases where you may want to return
// other types like a string slice instead of just a string.
func ProviderWithValue(prefix, delim string, cb func(key string, value string) (string, interface{})) *Env {
return &Env{
prefix: prefix,
delim: delim,
cb: cb,
return ProviderWithOptions(
WithPrefix(prefix),
WithDelimiter(delim),
WithCallback(cb),
)
}

// ProviderWithOptions returns an environment variables provider that can be fine-tuned
// by using options.
func ProviderWithOptions(options ...Option) *Env {
e := &Env{
prefix: "",
delim: ".",
cb: nil,
environFunc: func() []string {
return os.Environ()
},
}

for _, option := range options {
option(e)
}
return e
}

// ReadBytes is not supported by the env provider.
Expand All @@ -65,7 +81,7 @@ func (e *Env) ReadBytes() ([]byte, error) {
func (e *Env) Read() (map[string]interface{}, error) {
// Collect the environment variable keys.
var keys []string
for _, k := range os.Environ() {
for _, k := range e.environFunc() {
if e.prefix != "" {
if strings.HasPrefix(k, e.prefix) {
keys = append(keys, k)
Expand Down