Spaces:
Sleeping
Sleeping
import aiohttp | |
from aiohttp import web | |
from urllib.parse import urlparse | |
async def proxy_handler(request): | |
# Retrieve the URL from the query parameters | |
target_url = request.query.get('url') | |
if not target_url: | |
return web.Response(status=400, text="Missing 'url' query parameter.") | |
# Optional: Validate the URL schema | |
parsed_url = urlparse(target_url) | |
if parsed_url.scheme not in ['http', 'https']: | |
return web.Response(status=400, text="Invalid URL scheme. Only HTTP and HTTPS are supported.") | |
# Get the aiohttp ClientSession from the app | |
session = request.app['session'] | |
# Prepare the request headers, removing the host header | |
headers = dict(request.headers) | |
headers.pop('Host', None) | |
# Forward the request to the target URL | |
async with session.request( | |
method=request.method, | |
url=target_url, | |
headers=headers, | |
allow_redirects=False, | |
data=await request.read() # Forward the original payload as it is | |
) as response: | |
# Prepare the response headers, excluding 'Transfer-Encoding' and 'Content-Encoding' | |
response_headers = {k: v for k, v in response.headers.items() if k.lower() not in ['transfer-encoding', 'content-encoding']} | |
# Create a new aiohttp response | |
return web.Response( | |
status=response.status, | |
headers=response_headers, | |
body=await response.read() | |
) | |
async def create_session(app): | |
app['session'] = aiohttp.ClientSession() | |
async def close_session(app): | |
await app['session'].close() | |
app = web.Application() | |
app.add_routes([web.route('*', '/', proxy_handler)]) | |
app.on_startup.append(create_session) | |
app.on_cleanup.append(close_session) | |
if __name__ == '__main__': | |
web.run_app(app, port=8080) # Specify the port to run on |