2019-05-31 01:11:13 +03:00
|
|
|
package env
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"strings"
|
|
|
|
|
2020-01-30 14:39:00 +03:00
|
|
|
"github.com/micro/go-micro/v2/config/source"
|
2019-05-31 01:11:13 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type strippedPrefixKey struct{}
|
|
|
|
type prefixKey struct{}
|
|
|
|
|
|
|
|
// WithStrippedPrefix sets the environment variable prefixes to scope to.
|
|
|
|
// These prefixes will be removed from the actual config entries.
|
|
|
|
func WithStrippedPrefix(p ...string) source.Option {
|
|
|
|
return func(o *source.Options) {
|
|
|
|
if o.Context == nil {
|
|
|
|
o.Context = context.Background()
|
|
|
|
}
|
|
|
|
|
|
|
|
o.Context = context.WithValue(o.Context, strippedPrefixKey{}, appendUnderscore(p))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithPrefix sets the environment variable prefixes to scope to.
|
|
|
|
// These prefixes will not be removed. Each prefix will be considered a top level config entry.
|
|
|
|
func WithPrefix(p ...string) source.Option {
|
|
|
|
return func(o *source.Options) {
|
|
|
|
if o.Context == nil {
|
|
|
|
o.Context = context.Background()
|
|
|
|
}
|
|
|
|
o.Context = context.WithValue(o.Context, prefixKey{}, appendUnderscore(p))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func appendUnderscore(prefixes []string) []string {
|
2019-12-03 22:59:44 +03:00
|
|
|
//nolint:prealloc
|
2019-05-31 01:11:13 +03:00
|
|
|
var result []string
|
|
|
|
for _, p := range prefixes {
|
|
|
|
if !strings.HasSuffix(p, "_") {
|
|
|
|
result = append(result, p+"_")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
result = append(result, p)
|
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|