You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.0 KiB

4 years ago
package env
import (
"context"
"fmt"
4 years ago
"os"
"strings"
"gitoa.ru/go-4devs/config"
"gitoa.ru/go-4devs/config/value"
)
const Name = "env"
4 years ago
var _ config.Provider = (*Provider)(nil)
type Option func(*Provider)
func WithKeyFactory(factory func(...string) string) Option {
4 years ago
return func(p *Provider) { p.key = factory }
}
func New(namespace, appName string, opts ...Option) *Provider {
provider := Provider{
key: func(path ...string) string {
return strings.ToUpper(strings.Join(path, "_"))
4 years ago
},
prefix: strings.ToUpper(namespace + "_" + appName + "_"),
4 years ago
}
for _, opt := range opts {
opt(&provider)
4 years ago
}
return &provider
4 years ago
}
type Provider struct {
key func(...string) string
name string
prefix string
4 years ago
}
func (p *Provider) Name() string {
return p.name
4 years ago
}
9 months ago
func (p *Provider) Value(_ context.Context, path ...string) (config.Value, error) {
name := p.prefix + p.key(path...)
if val, ok := os.LookupEnv(name); ok {
return value.JString(val), nil
4 years ago
}
return nil, fmt.Errorf("%v:%w", p.Name(), config.ErrValueNotFound)
4 years ago
}