2024-02-04 18:19:19 -06:00
|
|
|
package config
|
|
|
|
|
|
|
|
|
|
import (
|
2026-03-08 22:59:33 -05:00
|
|
|
"bytes"
|
|
|
|
|
"context"
|
2024-02-09 09:44:35 -06:00
|
|
|
"fmt"
|
2026-03-08 22:59:33 -05:00
|
|
|
"strings"
|
2024-02-04 18:19:19 -06:00
|
|
|
|
2026-03-08 22:59:33 -05:00
|
|
|
"github.com/spf13/viper"
|
2024-02-04 18:19:19 -06:00
|
|
|
)
|
|
|
|
|
|
2026-03-08 22:59:33 -05:00
|
|
|
type confKeyType uint8
|
2024-02-04 18:19:19 -06:00
|
|
|
|
2026-03-08 22:59:33 -05:00
|
|
|
const (
|
|
|
|
|
_ confKeyType = iota
|
|
|
|
|
viperKey
|
|
|
|
|
)
|
2024-02-04 18:19:19 -06:00
|
|
|
|
2026-03-08 22:59:33 -05:00
|
|
|
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 {
|
2026-03-08 22:59:33 -05:00
|
|
|
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
|
|
|
}
|
|
|
|
|
|
2026-03-08 22:59:33 -05:00
|
|
|
v.SetConfigFile(DefaultPath())
|
|
|
|
|
v.SetEnvPrefix("MYLOG")
|
|
|
|
|
v.AutomaticEnv()
|
|
|
|
|
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
|
2024-02-10 11:48:23 -06:00
|
|
|
|
2026-03-08 22:59:33 -05:00
|
|
|
if err := v.ReadInConfig(); err != nil {
|
|
|
|
|
return ctx, nil, err
|
2024-03-07 21:19:45 -06:00
|
|
|
}
|
|
|
|
|
|
2026-03-08 22:59:33 -05:00
|
|
|
return AddToContext(ctx, v), v, nil
|
2024-03-07 21:19:45 -06:00
|
|
|
}
|