File size: 1,163 Bytes
ac09d69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from fastapi import FastAPI, Request, Response
import requests

app = FastAPI()

@app.get("/")
async def proxy(request: Request):
    target_url = request.query_params.get('url')
    if not target_url:
        return Response(content="Missing 'url' query parameter", status_code=400)

    try:
        resp = requests.get(target_url, headers={'User-Agent': 'Mozilla/5.0'})
        excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
        headers = {k: v for k, v in resp.headers.items() if k.lower() not in excluded_headers}

        content_type = resp.headers.get('content-type')
        if content_type and 'text/html' in content_type:
            text = resp.text
            text = text.replace('href="/', f'href="?url={target_url}/')
            text = text.replace('src="/', f'src="?url={target_url}/')
            return Response(content=text, headers=headers, status_code=resp.status_code)
        
        return Response(content=resp.content, headers=headers, status_code=resp.status_code)
    except Exception as e:
        return Response(content=f"Error fetching {target_url}: {str(e)}", status_code=500)