alchemyst/util/context.go
2019-10-17 19:57:20 +03:00

44 lines
887 B
Go

package util
import (
"context"
"fmt"
"github.com/rs/zerolog"
)
const (
configKey = "config"
loggerKey = "logger"
)
type ClientCtx struct {
ctx context.Context
}
func NewClientContext(config *Config, logger *zerolog.Logger) ClientCtx {
ctx := context.Context(context.TODO())
ctx = context.WithValue(ctx, configKey, config)
ctx = context.WithValue(ctx, loggerKey, logger)
return ClientCtx{ctx: ctx}
}
func (c *ClientCtx) Config() *Config {
cfg, ok := c.ctx.Value(configKey).(*Config)
if !ok {
panic(fmt.Errorf("no access to config from context"))
}
return cfg
}
func (c *ClientCtx) Logger() *zerolog.Logger {
logger, ok := c.ctx.Value(loggerKey).(*zerolog.Logger)
if !ok {
panic(fmt.Errorf("no access to logger from context"))
}
return logger
}
//func FromContext(ctx context.Context) (*User, bool) {
// u, ok := ctx.Value(userKey).(*User)
// return u, ok
//}