feat: handler proxy mecanism
This commit is contained in:
@@ -8,6 +8,9 @@ import pathlib
|
||||
import re
|
||||
import tarfile
|
||||
import typing
|
||||
import urllib.parse
|
||||
|
||||
import requests
|
||||
|
||||
from . import STAPLER_ASCII, logs, project
|
||||
from .data_dir import DataDir
|
||||
@@ -130,6 +133,39 @@ class BaseHandler(abc.ABC, http.server.BaseHTTPRequestHandler):
|
||||
headers={"Location": location},
|
||||
)
|
||||
|
||||
def send_proxy(self, url: str) -> None:
|
||||
body: bytes | None = None
|
||||
if self.in_size > 0:
|
||||
body = self.rfile.read(self.in_size)
|
||||
headers = dict(self.headers)
|
||||
headers["Host"] = urllib.parse.urlparse(url).netloc
|
||||
headers["X-Forwarded-For"] = self.client_address[0]
|
||||
headers["X-Real-IP"] = self.client_address[0]
|
||||
try:
|
||||
response: requests.Response = requests.request(
|
||||
self.command, url, data=body, headers=headers, timeout=240
|
||||
)
|
||||
except Exception as e:
|
||||
self.send_error(
|
||||
http.HTTPStatus.BAD_GATEWAY, f"Could not reach {url}", explain=str(e)
|
||||
)
|
||||
return
|
||||
self.send_response(response.status_code, response.reason)
|
||||
for header, value in response.headers.items():
|
||||
if header.lower() not in [
|
||||
"content-length",
|
||||
"content-encoding",
|
||||
"transfer-encoding",
|
||||
"server",
|
||||
"date",
|
||||
]:
|
||||
self.send_header(header, value)
|
||||
self.send_header("Content-Length", str(out_size := len(response.content)))
|
||||
self.end_headers()
|
||||
if out_size > 0:
|
||||
self.wfile.write(response.content)
|
||||
self.close_connection = True
|
||||
|
||||
@property
|
||||
def host(self) -> str:
|
||||
if self.__host is None:
|
||||
|
||||
Reference in New Issue
Block a user