package middleware import ( "context" "encoding/json" "net/url" context2 "git.ikuban.com/server/kratos-utils/http/context" "github.com/go-kratos/kratos/v2/middleware" "google.golang.org/grpc/metadata" ) //GetUserID 为userid func GetUserID(c context.Context) string { userID := c.Value("user_id") if _, ok := userID.(string); ok { return userID.(string) } return "" } func GetAccountID(c context.Context) string { accountID := c.Value("account_id") if _, ok := accountID.(string); ok { return accountID.(string) } return "" } func GetAuthToken(c context.Context) string { token := c.Value("auth_token") if _, ok := token.(string); ok { return token.(string) } return "" } func GetJwtClaims(c context.Context) json.RawMessage { claim := c.Value("jwt_claims") if _, ok := claim.(json.RawMessage); ok { return claim.(json.RawMessage) } return []byte{} } func GetPageOffset(c context.Context) (string, int64) { nextId := c.Value("nextId") offset := c.Value("offset") _nextId := "" _offset := int64(0) if _, ok := nextId.(string); ok { _nextId = nextId.(string) } if _, ok := offset.(int64); ok { _offset = offset.(int64) } return _nextId, _offset } func GrpcValue(handler middleware.Handler) middleware.Handler { return func(ctx context.Context, req interface{}) (reply interface{}, err error) { if md, ok := metadata.FromIncomingContext(ctx); ok { userID := md.Get("user_id") if len(userID) > 0 { ctx = context2.AppendToContext(ctx, "userId", userID[0]) } accountID := md.Get("account_id") if len(accountID) > 0 { ctx = context2.AppendToContext(ctx, "accountId", accountID[0]) } claimMap := md.Get("jwt_claims") if len(claimMap) > 0 { _claimMap := json.RawMessage(claimMap[0]) ctx = context2.AppendToContext(ctx, "jwt_claims", _claimMap) } token := md.Get("auth_token") if len(token) > 0 { ctx = context2.AppendToContext(ctx, "auth_token", token[0]) } //nextId := md.Get("nextId") //if len(nextId) > 0 { // ctx = context2.AppendToContext(ctx, "nextId", nextId[0]) //} // //offset := md.Get("offset") //if len(offset) > 0 { // _offset, _ := strconv.ParseInt(offset[0], 10, 64) // ctx = context2.AppendToContext(ctx, "offset", _offset) //} query := md.Get("query") if len(query) > 0 { _query, _ := url.ParseQuery(query[0]) ctx = context2.AppendToContext(ctx, "query", _query) } referer := md.Get("referer") if len(referer) > 0 { ctx = context2.AppendToContext(ctx, "referer", referer[0]) } uri := md.Get("uri") if len(uri) > 0 { ctx = context2.AppendToContext(ctx, "uri", uri[0]) } userAgent := md.Get("user_agent") if len(uri) > 0 { ctx = context2.AppendToContext(ctx, "userAgent", userAgent[0]) } } return handler(ctx, req) } }