my-log/config/load.go

53 lines
1 KiB
Go
Raw Normal View History

package config
import (
"bytes"
"context"
2024-02-09 09:44:35 -06:00
"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)
2024-02-10 11:06:00 -06:00
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) (context.Context, *viper.Viper, error) {
v := viper.New()
v.SetConfigType("toml")
if err := v.ReadConfig(bytes.NewBufferString(DefaultStr())); err != nil {
return ctx, nil, err
2024-02-10 11:06:00 -06:00
}
v.SetConfigFile(DefaultPath())
v.SetEnvPrefix("MYLOG")
v.AutomaticEnv()
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
if err := v.ReadInConfig(); err != nil {
return ctx, nil, err
2024-03-07 21:19:45 -06:00
}
return AddToContext(ctx, v), v, nil
2024-03-07 21:19:45 -06:00
}