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

92 lines
2.3 KiB
Go

package config
import (
"context"
"errors"
"reflect"
)
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)
}
// Add to Ctx for custom type that embeds AppConfig
func AddToContextFor[T any](ctx context.Context, cfg T) context.Context {
return context.WithValue(ctx, appConfigCtxKey, cfg)
}
// FromCtxFor retrieves custom config that embeds AppConfig from context
func FromCtxFor[T any](ctx context.Context) (*T, error) {
ctxData := ctx.Value(appConfigCtxKey)
if ctxData == nil {
return nil, errors.New("no config found in context")
}
cfg, ok := ctxData.(*T)
if !ok {
return nil, errors.New("invalid config stored in context")
}
return cfg, nil
}
// MustFromCtxFor retrieves custom config that embeds AppConfig from context, or panics if not found.
func MustFromCtxFor[T any](ctx context.Context) *T {
cfg, err := FromCtxFor[T](ctx)
if err != nil {
panic(err)
}
return cfg
}
// 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.
// It handles both direct *AppConfig and custom types that embed *AppConfig.
func FromCtx(ctx context.Context) (*AppConfig, error) {
ctxData := ctx.Value(appConfigCtxKey)
if ctxData == nil {
return nil, errors.New("no config found in context")
}
// Try direct type assertion first
if cfg, ok := ctxData.(*AppConfig); ok {
return cfg, nil
}
// Try to extract *AppConfig from a custom type that embeds it
v := reflect.ValueOf(ctxData)
if v.Kind() != reflect.Pointer || v.IsNil() {
return nil, errors.New("invalid config stored in context: must be a non-nil pointer")
}
v = v.Elem()
if v.Kind() != reflect.Struct {
return nil, errors.New("invalid config stored in context: must be a pointer to a struct")
}
// Look for *AppConfig field
for i := range v.NumField() {
field := v.Field(i)
if field.Type() == reflect.TypeFor[*AppConfig]() {
if appConfig, ok := field.Interface().(*AppConfig); ok {
return appConfig, nil
}
}
}
return nil, errors.New("no *AppConfig found in context value")
}