package util import ( "context" "gitea.com/red-future/common/utils" "github.com/gogf/gf/v2/frame/g" ) // AsyncCtx 固化异步上下文中的 token 和用户信息,避免请求结束后丢失 func AsyncCtx(ctx context.Context) context.Context { asyncCtx := context.WithoutCancel(ctx) if r := g.RequestFromCtx(ctx); r != nil { if token := r.Header.Get("Authorization"); token != "" { asyncCtx = context.WithValue(asyncCtx, "token", token) } if userInfo := r.Header.Get("X-User-Info"); userInfo != "" { asyncCtx = context.WithValue(asyncCtx, "xUserInfo", userInfo) } } if user, err := utils.GetUserInfo(ctx); err == nil && user != nil { asyncCtx = context.WithValue(asyncCtx, "user", user) } return asyncCtx } // ForwardHeaders 透传调用链路的头信息,优先使用 ctx 中的固化值 func ForwardHeaders(ctx context.Context) map[string]string { headers := make(map[string]string) if token, ok := ctx.Value("token").(string); ok && token != "" { headers["Authorization"] = token } if x, ok := ctx.Value("xUserInfo").(string); ok && x != "" { headers["X-User-Info"] = x } // 兜底:从请求头获取 if r := g.RequestFromCtx(ctx); r != nil { if headers["Authorization"] == "" { if token := r.Header.Get("Authorization"); token != "" { headers["Authorization"] = token } } if headers["X-User-Info"] == "" { if userInfo := r.Header.Get("X-User-Info"); userInfo != "" { headers["X-User-Info"] = userInfo } } } return headers }