frostfs-http-gw/utils/util.go
Roman Loginov fc86ab3511
All checks were successful
/ DCO (pull_request) Successful in 1m7s
/ Builds (pull_request) Successful in 1m3s
/ Vulncheck (pull_request) Successful in 1m34s
/ Lint (pull_request) Successful in 2m6s
/ Tests (pull_request) Successful in 1m11s
[#148] Add trace_id to logs
Signed-off-by: Roman Loginov <r.loginov@yadro.com>
2024-10-17 11:00:43 +00:00

49 lines
1.2 KiB
Go

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
}