57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
package util
|
|
|
|
import (
|
|
"context"
|
|
"net/url"
|
|
|
|
"gitea.redpowerfuture.com/red-future/common/utils"
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
"github.com/gogf/gf/v2/util/gconv"
|
|
)
|
|
|
|
// 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
|
|
}
|
|
|
|
// ======================== 请求工具 ========================
|
|
|
|
// ParseHeadMsgHeaders 从 head_msg 中提取 HTTP 请求头
|
|
func ParseHeadMsgHeaders(headMsg map[string]any) map[string]string {
|
|
if len(headMsg) == 0 {
|
|
return nil
|
|
}
|
|
out := make(map[string]string, len(headMsg))
|
|
for k, v := range headMsg {
|
|
out[k] = gconv.String(v)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// BodyToQuery 将 body 转为 URL 查询参数
|
|
func BodyToQuery(payload map[string]any) (url.Values, error) {
|
|
q := url.Values{}
|
|
for k, v := range payload {
|
|
if v == nil {
|
|
continue
|
|
}
|
|
q.Set(k, gconv.String(v))
|
|
}
|
|
return q, nil
|
|
}
|