add FromContext API for macaron and reqcontext, add API for standard middleware in macaron (#37057)

This commit is contained in:
Serge Zaitsev
2021-07-26 06:11:43 +02:00
committed by GitHub
parent f78452be30
commit 827a5b7021
2 changed files with 52 additions and 1 deletions

View File

@@ -62,6 +62,16 @@ func (h *ContextHandler) Init() error {
return nil
}
type reqContextKey struct{}
// FromContext returns the ReqContext value stored in a context.Context, if any.
func FromContext(c context.Context) *models.ReqContext {
if reqCtx, ok := c.Value(reqContextKey{}).(*models.ReqContext); ok {
return reqCtx
}
return nil
}
// Middleware provides a middleware to initialize the Macaron context.
func (h *ContextHandler) Middleware(mContext *macaron.Context) {
span, _ := opentracing.StartSpanFromContext(mContext.Req.Context(), "Auth - Middleware")
@@ -76,6 +86,10 @@ func (h *ContextHandler) Middleware(mContext *macaron.Context) {
Logger: log.New("context"),
}
// Inject ReqContext into a request context and replace the request instance in the macaron context
mContext.Req.Request = mContext.Req.WithContext(context.WithValue(mContext.Req.Context(), reqContextKey{}, reqContext))
mContext.Map(mContext.Req.Request)
traceID, exists := cw.ExtractTraceID(mContext.Req.Request.Context())
if exists {
reqContext.Logger = reqContext.Logger.New("traceID", traceID)