1. import logging
  2. # Configure logging
  3. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  4. def truncate_headers(headers, max_size=2048):
  5. """
  6. Truncates request headers exceeding a specified size.
  7. Args:
  8. headers (dict): A dictionary of request headers.
  9. max_size (int): The maximum size (in bytes) allowed for the combined headers.
  10. Returns:
  11. dict: A dictionary of truncated headers.
  12. """
  13. truncated_headers = {}
  14. total_size = 0
  15. for key, value in headers.items():
  16. if isinstance(value, str):
  17. value_bytes = value.encode('utf-8') # Encode string to bytes
  18. else:
  19. value_bytes = str(value).encode('utf-8') #handle non-string values
  20. header_size = len(value_bytes)
  21. if total_size + header_size > max_size:
  22. if key in truncated_headers:
  23. # Truncate existing header
  24. truncated_headers[key] += "..." if truncated_headers[key] else "" #add ellipsis if not empty
  25. else:
  26. truncated_headers[key] = "..." # Add ellipsis if new header
  27. total_size = max_size #reset total size
  28. truncated_headers[key] = value #keep original value for output
  29. total_size += header_size
  30. return truncated_headers
  31. if __name__ == '__main__':
  32. # Example Usage
  33. headers = {
  34. "Content-Type": "application/json",
  35. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
  36. "X-Custom-Header": "This is a very long header value to test truncation.",
  37. "Another-Header": "Short value"
  38. }
  39. truncated = truncate_headers(headers)
  40. print(truncated)
  41. #Example with non-string value
  42. headers2 = {
  43. "Content-Type": "application/json",
  44. "User-Agent": 12345,
  45. "X-Custom-Header": "This is a very long header value to test truncation.",
  46. }
  47. truncated2 = truncate_headers(headers2)
  48. print(truncated2)
  49. #Example of header exceeding max_size
  50. headers3 = {
  51. "Content-Type": "application/json",
  52. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
  53. "X-Custom-Header": "This is a very long header value to test truncation." * 100, #long string
  54. }
  55. truncated3 = truncate_headers(headers3)
  56. print(truncated3)

Add your comment