1. import argparse
  2. import json
  3. import sys
  4. import re
  5. def normalize_headers(headers):
  6. """Normalizes request headers: lowercase, remove whitespace, and standardize values."""
  7. normalized_headers = {}
  8. for key, value in headers.items():
  9. # Lowercase the key
  10. key = key.lower().strip()
  11. # Remove whitespace from the value
  12. value = value.strip()
  13. # Standardize common values (example: 'true' to 'True')
  14. if value.lower() == 'true':
  15. value = 'True'
  16. elif value.lower() == 'false':
  17. value = 'False'
  18. normalized_headers[key] = value
  19. return normalized_headers
  20. def main():
  21. parser = argparse.ArgumentParser(description="Normalize request headers for non-production use.")
  22. parser.add_argument("input_file", help="Path to the input JSON file containing headers.")
  23. parser.add_argument("-o", "--output_file", help="Path to the output JSON file.")
  24. parser.add_argument("-i", "--input_string", help="Input headers as a JSON string.")
  25. args = parser.parse_args()
  26. try:
  27. if args.input_string:
  28. headers = json.loads(args.input_string)
  29. else:
  30. with open(args.input_file, "r") as f:
  31. headers = json.load(f)
  32. except FileNotFoundError:
  33. print(f"Error: Input file '{args.input_file}' not found.")
  34. sys.exit(1)
  35. except json.JSONDecodeError:
  36. print(f"Error: Invalid JSON in '{args.input_file}'.")
  37. sys.exit(1)
  38. normalized_headers = normalize_headers(headers)
  39. if args.output_file:
  40. try:
  41. with open(args.output_file, "w") as f:
  42. json.dump(normalized_headers, f, indent=4)
  43. print(f"Normalized headers written to '{args.output_file}'")
  44. except IOError:
  45. print(f"Error: Could not write to output file '{args.output_file}'.")
  46. sys.exit(1)
  47. else:
  48. print(json.dumps(normalized_headers, indent=4))
  49. if __name__ == "__main__":
  50. main()

Add your comment