Files
mayfly-go/server/pkg/contextx/contextx.go

48 lines
1.1 KiB
Go
Raw Normal View History

package contextx
import (
"context"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/stringx"
)
type CtxKey string
const (
LoginAccountKey CtxKey = "loginAccount"
TraceIdKey CtxKey = "traceId"
)
func NewLoginAccount(la *model.LoginAccount) context.Context {
return WithLoginAccount(context.Background(), la)
}
func WithLoginAccount(ctx context.Context, la *model.LoginAccount) context.Context {
return context.WithValue(ctx, LoginAccountKey, la)
}
2024-11-20 22:43:53 +08:00
// GetLoginAccount 从context中获取登录账号信息不存在返回nil
func GetLoginAccount(ctx context.Context) *model.LoginAccount {
if la, ok := ctx.Value(LoginAccountKey).(*model.LoginAccount); ok {
return la
}
return nil
}
func NewTraceId() context.Context {
return WithTraceId(context.Background())
}
2024-11-20 22:43:53 +08:00
// WithTraceId 将traceId放置context中
func WithTraceId(ctx context.Context) context.Context {
return context.WithValue(ctx, TraceIdKey, stringx.RandByChars(16, stringx.Nums+stringx.LowerChars))
}
// 从context中获取traceId
func GetTraceId(ctx context.Context) string {
if val, ok := ctx.Value(TraceIdKey).(string); ok {
return val
}
return ""
}