|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +An example of how to modify HTTP headers with asyncio-https-proxy. |
| 4 | +
|
| 5 | +This example demonstrates how to create a custom proxy handler to intercept |
| 6 | +and modify HTTP requests before they are forwarded to the destination server. |
| 7 | +""" |
| 8 | + |
| 9 | +import asyncio |
| 10 | + |
| 11 | +from asyncio_https_proxy import HTTPSForwardProxyHandler, TLSStore, start_proxy_server |
| 12 | + |
| 13 | + |
| 14 | +class ModifyHeaderHandler(HTTPSForwardProxyHandler): |
| 15 | + """ |
| 16 | + A custom proxy handler that adds a 'X-Custom-Header' to all requests. |
| 17 | + """ |
| 18 | + |
| 19 | + async def on_request_received(self): |
| 20 | + """ |
| 21 | + Intercept the request and add a custom header. |
| 22 | + """ |
| 23 | + print(f"Original request headers for {self.request.url()}:") |
| 24 | + for key, value in self.request.headers: |
| 25 | + print(f" {key}: {value}") |
| 26 | + |
| 27 | + # Add a custom header to the request |
| 28 | + self.request.headers.headers.append( |
| 29 | + ("X-Custom-Header", "Hello from the proxy!") |
| 30 | + ) |
| 31 | + |
| 32 | + print("\nModified request headers:") |
| 33 | + for key, value in self.request.headers: |
| 34 | + print(f" {key}: {value}") |
| 35 | + print("---") |
| 36 | + |
| 37 | + # Continue with the default request forwarding |
| 38 | + await super().on_request_received() |
| 39 | + |
| 40 | + |
| 41 | +async def main(): |
| 42 | + """ |
| 43 | + Run the modifying forward proxy. |
| 44 | + """ |
| 45 | + |
| 46 | + host = "127.0.0.1" |
| 47 | + port = 8888 |
| 48 | + |
| 49 | + print(f"Starting HTTPS forward proxy on {host}:{port}") |
| 50 | + print("This proxy will add a 'X-Custom-Header' to all requests.") |
| 51 | + print("\nTest the proxy with:") |
| 52 | + print(f" curl --insecure --proxy http://{host}:{port} https://httpbin.org/headers") |
| 53 | + print("\nPress Ctrl+C to stop the proxy") |
| 54 | + |
| 55 | + # Initialize the TLS store for HTTPS interception |
| 56 | + tls_store = TLSStore.generate_ca( |
| 57 | + country="FR", |
| 58 | + state="Ile-de-France", |
| 59 | + locality="Paris", |
| 60 | + organization="Modify Header Example", |
| 61 | + common_name="Modify Header CA", |
| 62 | + ) |
| 63 | + |
| 64 | + server = await start_proxy_server( |
| 65 | + handler_builder=lambda: ModifyHeaderHandler(), |
| 66 | + host=host, |
| 67 | + port=port, |
| 68 | + tls_store=tls_store, |
| 69 | + ) |
| 70 | + |
| 71 | + async with server: |
| 72 | + try: |
| 73 | + await server.serve_forever() |
| 74 | + except KeyboardInterrupt: |
| 75 | + print("Shutting down proxy...") |
| 76 | + server.close() |
| 77 | + await server.wait_closed() |
| 78 | + print("Proxy shut down.") |
| 79 | + |
| 80 | + |
| 81 | +if __name__ == "__main__": |
| 82 | + asyncio.run(main()) |
0 commit comments