rpc_value.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package middleware
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/url"
  6. "strconv"
  7. context2 "git.ikuban.com/server/kratos-utils/http/context"
  8. "google.golang.org/grpc/metadata"
  9. "github.com/go-kratos/kratos/v2/middleware"
  10. )
  11. func GrpcValue(handler middleware.Handler) middleware.Handler {
  12. return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
  13. if md, ok := metadata.FromIncomingContext(ctx); ok {
  14. userID := md.Get("user_id")
  15. if len(userID) > 0 {
  16. _userID, _ := strconv.ParseInt(userID[0], 10, 64)
  17. ctx = context2.AppendToContext(ctx, "user_id", _userID)
  18. }
  19. claimMap := md.Get("jwt_claims")
  20. if len(claimMap) > 0 {
  21. _claimMap := json.RawMessage(claimMap[0])
  22. ctx = context2.AppendToContext(ctx, "jwt_claims", _claimMap)
  23. }
  24. token := md.Get("auth_token")
  25. if len(token) > 0 {
  26. ctx = context2.AppendToContext(ctx, "auth_token", token[0])
  27. }
  28. page := md.Get("page")
  29. if len(page) > 0 {
  30. _page, _ := strconv.ParseInt(page[0], 10, 64)
  31. ctx = context2.AppendToContext(ctx, "page", _page)
  32. }
  33. pageSize := md.Get("page_size")
  34. if len(pageSize) > 0 {
  35. _pageSize, _ := strconv.ParseInt(pageSize[0], 10, 64)
  36. ctx = context2.AppendToContext(ctx, "page_size", _pageSize)
  37. }
  38. query := md.Get("query")
  39. if len(query) > 0 {
  40. _query, _ := url.ParseQuery(query[0])
  41. ctx = context2.AppendToContext(ctx, "query", _query)
  42. }
  43. }
  44. return handler(ctx, req)
  45. }
  46. }