import argparse
import json
import sys
import re
def normalize_headers(headers):
"""Normalizes request headers: lowercase, remove whitespace, and standardize values."""
normalized_headers = {}
for key, value in headers.items():
# Lowercase the key
key = key.lower().strip()
# Remove whitespace from the value
value = value.strip()
# Standardize common values (example: 'true' to 'True')
if value.lower() == 'true':
value = 'True'
elif value.lower() == 'false':
value = 'False'
normalized_headers[key] = value
return normalized_headers
def main():
parser = argparse.ArgumentParser(description="Normalize request headers for non-production use.")
parser.add_argument("input_file", help="Path to the input JSON file containing headers.")
parser.add_argument("-o", "--output_file", help="Path to the output JSON file.")
parser.add_argument("-i", "--input_string", help="Input headers as a JSON string.")
args = parser.parse_args()
try:
if args.input_string:
headers = json.loads(args.input_string)
else:
with open(args.input_file, "r") as f:
headers = json.load(f)
except FileNotFoundError:
print(f"Error: Input file '{args.input_file}' not found.")
sys.exit(1)
except json.JSONDecodeError:
print(f"Error: Invalid JSON in '{args.input_file}'.")
sys.exit(1)
normalized_headers = normalize_headers(headers)
if args.output_file:
try:
with open(args.output_file, "w") as f:
json.dump(normalized_headers, f, indent=4)
print(f"Normalized headers written to '{args.output_file}'")
except IOError:
print(f"Error: Could not write to output file '{args.output_file}'.")
sys.exit(1)
else:
print(json.dumps(normalized_headers, indent=4))
if __name__ == "__main__":
main()
Add your comment