Go app framework
This commit is contained in:
36
pkg/config/ctx.go
Normal file
36
pkg/config/ctx.go
Normal file
@ -0,0 +1,36 @@
|
||||
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
|
||||
}
|
Reference in New Issue
Block a user