go-http-server-with-otel/pkg/config/ctx.go

29 lines
541 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 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
}