enhance context management for custom types

This commit is contained in:
2025-12-24 10:47:28 -05:00
parent 70e99eef0e
commit 98650211ac
2 changed files with 41 additions and 5 deletions

View File

@@ -14,6 +14,41 @@ 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 interface {
*AppConfig
}](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 interface {
*AppConfig
}](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 interface {
*AppConfig
}](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)