grpc_header.go 883 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package utils
  2. import (
  3. "context"
  4. "github.com/google/uuid"
  5. "google.golang.org/grpc/metadata"
  6. )
  7. const (
  8. // RequestIDKey requestID key
  9. RequestIDKey = "x-request-id"
  10. // UsernameKey username key
  11. UsernameKey = "x-username"
  12. )
  13. // GetRequestID request id from header
  14. func GetRequestID(ctx context.Context) string {
  15. id := GetHeaderFirst(ctx, RequestIDKey)
  16. if id == "" {
  17. id = NewRequestID()
  18. }
  19. return id
  20. }
  21. // GetUsername get username from header
  22. func GetUsername(ctx context.Context) string {
  23. return GetHeaderFirst(ctx, UsernameKey)
  24. }
  25. // GetHeaderFirst get header first value
  26. func GetHeaderFirst(ctx context.Context, key string) string {
  27. if md, ok := metadata.FromIncomingContext(ctx); ok {
  28. if values := md.Get(key); len(values) > 0 {
  29. return values[0]
  30. }
  31. }
  32. return ""
  33. }
  34. // NewRequestID generate a RequestId
  35. func NewRequestID() string {
  36. return uuid.New().String()
  37. }