frostfs-http-gw/utils/util.go

50 lines
1.2 KiB
Go
Raw Normal View History

package utils
import (
"context"
"github.com/valyala/fasthttp"
"go.uber.org/zap"
)
// SetContextToRequest adds new context to fasthttp request.
func SetContextToRequest(ctx context.Context, c *fasthttp.RequestCtx) {
c.SetUserValue("context", ctx)
}
// GetContextFromRequest returns main context from fasthttp request context.
func GetContextFromRequest(c *fasthttp.RequestCtx) context.Context {
return c.UserValue("context").(context.Context)
}
type ctxReqLoggerKeyType struct{}
// SetReqLog sets child zap.Logger in the context.
func SetReqLog(ctx context.Context, log *zap.Logger) context.Context {
if ctx == nil {
return nil
}
return context.WithValue(ctx, ctxReqLoggerKeyType{}, log)
}
// GetReqLog returns log if set.
// If zap.Logger isn't set returns nil.
func GetReqLog(ctx context.Context) *zap.Logger {
if ctx == nil {
return nil
} else if r, ok := ctx.Value(ctxReqLoggerKeyType{}).(*zap.Logger); ok {
return r
}
return nil
}
// GetReqLogOrDefault returns log from context, if it exists.
// If the log is missing from the context, the default logger is returned.
func GetReqLogOrDefault(ctx context.Context, defaultLog *zap.Logger) *zap.Logger {
log := GetReqLog(ctx)
if log == nil {
log = defaultLog
}
return log
}