57 lines
1.1 KiB
Go
57 lines
1.1 KiB
Go
package config
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type confKeyType uint8
|
|
|
|
const (
|
|
_ confKeyType = iota
|
|
viperKey
|
|
)
|
|
|
|
func RetrieveFromContext(ctx context.Context) (*viper.Viper, Config) {
|
|
v, ok := ctx.Value(viperKey).(*viper.Viper)
|
|
if !ok {
|
|
panic("config not found in context")
|
|
}
|
|
var c Config
|
|
if err := v.Unmarshal(&c); err != nil {
|
|
panic(fmt.Errorf("failed to unmarshal config: %w", err))
|
|
}
|
|
return v, c
|
|
}
|
|
|
|
func AddToContext(ctx context.Context, v *viper.Viper) context.Context {
|
|
return context.WithValue(ctx, viperKey, v)
|
|
}
|
|
|
|
func New(ctx context.Context, path string) (context.Context, *viper.Viper, error) {
|
|
v := viper.New()
|
|
v.SetConfigType("toml")
|
|
|
|
if err := v.ReadConfig(bytes.NewBufferString(DefaultStr())); err != nil {
|
|
return ctx, nil, err
|
|
}
|
|
|
|
if path == "" {
|
|
path = DefaultPath()
|
|
}
|
|
|
|
v.SetConfigFile(path)
|
|
v.SetEnvPrefix("MYLOG")
|
|
v.AutomaticEnv()
|
|
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
|
|
|
|
if err := v.MergeInConfig(); err != nil {
|
|
return ctx, nil, err
|
|
}
|
|
|
|
return AddToContext(ctx, v), v, nil
|
|
}
|