go-app/pkg/config/ctx.go
2025-01-04 12:24:42 -05:00

37 lines
666 B
Go

package config
import (
"context"
"errors"
)
type appConfigKey uint8
const appConfigCtxKey appConfigKey = iota
func (a *AppConfig) AddToCtx(ctx context.Context) context.Context {
return context.WithValue(ctx, appConfigCtxKey, a)
}
func MustFromCtx(ctx context.Context) *AppConfig {
cfg, err := FromCtx(ctx)
if err != nil {
panic(err)
}
return cfg
}
func FromCtx(ctx context.Context) (*AppConfig, error) {
ctxData := ctx.Value(appConfigCtxKey)
if ctxData == nil {
return nil, errors.New("no config found in context")
}
cfg, ok := ctxData.(*AppConfig)
if !ok {
return nil, errors.New("invalid config stored in context")
}
return cfg, nil
}