This commit is contained in:
61
provider/env/provider.go
vendored
Normal file
61
provider/env/provider.go
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
package env
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"gitoa.ru/go-4devs/config"
|
||||
"gitoa.ru/go-4devs/config/key"
|
||||
"gitoa.ru/go-4devs/config/value"
|
||||
)
|
||||
|
||||
var _ config.Provider = (*Provider)(nil)
|
||||
|
||||
type Option func(*Provider)
|
||||
|
||||
func WithKeyFactory(factory config.KeyFactory) Option {
|
||||
return func(p *Provider) { p.key = factory }
|
||||
}
|
||||
|
||||
func New(opts ...Option) *Provider {
|
||||
p := Provider{
|
||||
key: func(ctx context.Context, k config.Key) string {
|
||||
return strings.ToUpper(key.NsAppName("_")(ctx, k))
|
||||
},
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&p)
|
||||
}
|
||||
|
||||
return &p
|
||||
}
|
||||
|
||||
type Provider struct {
|
||||
key config.KeyFactory
|
||||
}
|
||||
|
||||
func (p *Provider) Name() string {
|
||||
return "env"
|
||||
}
|
||||
|
||||
func (p *Provider) IsSupport(ctx context.Context, key config.Key) bool {
|
||||
return p.key(ctx, key) != ""
|
||||
}
|
||||
|
||||
func (p *Provider) Read(ctx context.Context, key config.Key) (config.Variable, error) {
|
||||
k := p.key(ctx, key)
|
||||
if val, ok := os.LookupEnv(k); ok {
|
||||
return config.Variable{
|
||||
Name: k,
|
||||
Provider: p.Name(),
|
||||
Value: value.JString(val),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return config.Variable{
|
||||
Name: k,
|
||||
Provider: p.Name(),
|
||||
}, config.ErrVariableNotFound
|
||||
}
|
||||
24
provider/env/provider_test.go
vendored
Normal file
24
provider/env/provider_test.go
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
package env_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"gitoa.ru/go-4devs/config/provider/env"
|
||||
"gitoa.ru/go-4devs/config/test"
|
||||
)
|
||||
|
||||
func TestProvider(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
os.Setenv("FDEVS_CONFIG_DSN", test.DSN)
|
||||
os.Setenv("FDEVS_CONFIG_PORT", "8080")
|
||||
|
||||
provider := env.New()
|
||||
|
||||
read := []test.Read{
|
||||
test.NewRead("dsn", test.DSN),
|
||||
test.NewRead("port", 8080),
|
||||
}
|
||||
test.Run(t, provider, read)
|
||||
}
|
||||
Reference in New Issue
Block a user