rpc_value.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package middleware
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/url"
  6. "strconv"
  7. context2 "git.ikuban.com/server/kratos-utils/v2/transport/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. accountID := md.Get("account_id")
  20. if len(accountID) > 0 {
  21. _accountID, _ := strconv.ParseInt(accountID[0], 10, 64)
  22. ctx = context2.AppendToContext(ctx, "account_id", _accountID)
  23. }
  24. memID := md.Get("mem_id")
  25. if len(memID) > 0 {
  26. _memID, _ := strconv.ParseInt(memID[0], 10, 64)
  27. ctx = context2.AppendToContext(ctx, "mem_id", _memID)
  28. }
  29. claimMap := md.Get("jwt_claims")
  30. if len(claimMap) > 0 {
  31. _claimMap := json.RawMessage(claimMap[0])
  32. ctx = context2.AppendToContext(ctx, "jwt_claims", _claimMap)
  33. }
  34. token := md.Get("auth_token")
  35. if len(token) > 0 {
  36. ctx = context2.AppendToContext(ctx, "auth_token", token[0])
  37. }
  38. page := md.Get("page")
  39. if len(page) > 0 {
  40. _page, _ := strconv.ParseInt(page[0], 10, 64)
  41. ctx = context2.AppendToContext(ctx, "page", _page)
  42. }
  43. pageSize := md.Get("page_size")
  44. if len(pageSize) > 0 {
  45. _pageSize, _ := strconv.ParseInt(pageSize[0], 10, 64)
  46. ctx = context2.AppendToContext(ctx, "page_size", _pageSize)
  47. }
  48. query := md.Get("query")
  49. if len(query) > 0 {
  50. _query, _ := url.ParseQuery(query[0])
  51. ctx = context2.AppendToContext(ctx, "query", _query)
  52. }
  53. referer := md.Get("referer")
  54. if len(referer) > 0 {
  55. ctx = context2.AppendToContext(ctx, "referer", referer[0])
  56. }
  57. uri := md.Get("uri")
  58. if len(uri) > 0 {
  59. ctx = context2.AppendToContext(ctx, "uri", uri[0])
  60. }
  61. }
  62. return handler(ctx, req)
  63. }
  64. }