2022-04-20 09:17:20 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
2023-05-30 14:01:20 +00:00
|
|
|
"github.com/valyala/fasthttp"
|
2024-10-08 09:08:39 +00:00
|
|
|
"go.uber.org/zap"
|
2022-04-20 09:17:20 +00:00
|
|
|
)
|
|
|
|
|
2023-05-30 14:01:20 +00:00
|
|
|
// 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)
|
|
|
|
}
|
2024-10-08 09:08:39 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|