import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def truncate_headers(headers, max_size=2048):
"""
Truncates request headers exceeding a specified size.
Args:
headers (dict): A dictionary of request headers.
max_size (int): The maximum size (in bytes) allowed for the combined headers.
Returns:
dict: A dictionary of truncated headers.
"""
truncated_headers = {}
total_size = 0
for key, value in headers.items():
if isinstance(value, str):
value_bytes = value.encode('utf-8') # Encode string to bytes
else:
value_bytes = str(value).encode('utf-8') #handle non-string values
header_size = len(value_bytes)
if total_size + header_size > max_size:
if key in truncated_headers:
# Truncate existing header
truncated_headers[key] += "..." if truncated_headers[key] else "" #add ellipsis if not empty
else:
truncated_headers[key] = "..." # Add ellipsis if new header
total_size = max_size #reset total size
truncated_headers[key] = value #keep original value for output
total_size += header_size
return truncated_headers
if __name__ == '__main__':
# Example Usage
headers = {
"Content-Type": "application/json",
"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",
"X-Custom-Header": "This is a very long header value to test truncation.",
"Another-Header": "Short value"
}
truncated = truncate_headers(headers)
print(truncated)
#Example with non-string value
headers2 = {
"Content-Type": "application/json",
"User-Agent": 12345,
"X-Custom-Header": "This is a very long header value to test truncation.",
}
truncated2 = truncate_headers(headers2)
print(truncated2)
#Example of header exceeding max_size
headers3 = {
"Content-Type": "application/json",
"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",
"X-Custom-Header": "This is a very long header value to test truncation." * 100, #long string
}
truncated3 = truncate_headers(headers3)
print(truncated3)
Add your comment