Files
go-app/pkg/config/ctx.go

40 lines
858 B
Go

package config
import (
"context"
"errors"
)
type appConfigKey uint8
const appConfigCtxKey appConfigKey = iota
// AddToCtx adds the AppConfig to the provided context.
func (ac *AppConfig) AddToCtx(ctx context.Context) context.Context {
return context.WithValue(ctx, appConfigCtxKey, ac)
}
// MustFromCtx retrieves the AppConfig from the context, or panics if not found.
func MustFromCtx(ctx context.Context) *AppConfig {
cfg, err := FromCtx(ctx)
if err != nil {
panic(err)
}
return cfg
}
// FromCtx retrieves the AppConfig from the context.
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
}