Skip to content

Commit 203e91b

Browse files
committed
example: add proxy/httpproxy
1 parent b5ba1a4 commit 203e91b

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

example/proxy/httpproxy.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# coding:utf-8
2+
3+
from http.server import BaseHTTPRequestHandler
4+
from http.server import ThreadingHTTPServer
5+
6+
from xhtml import RequestProxy
7+
8+
PROXY: RequestProxy = RequestProxy("https://example.com/")
9+
10+
11+
class HTTPRequestProxy(BaseHTTPRequestHandler):
12+
13+
def do_GET(self):
14+
print(f"GET Path: {self.path}")
15+
print("request.headers:\n%s", self.headers)
16+
headers = PROXY.filter_headers({k: v for k, v in self.headers.items()})
17+
response = PROXY.request(path=self.path,
18+
method="GET",
19+
data=self.da,
20+
headers=headers
21+
).response
22+
self.send_response(response.status_code)
23+
print(response.status_code)
24+
for header, value in response.headers.items():
25+
self.send_header(header, value)
26+
print(f"{header}: {value}")
27+
self.end_headers()
28+
self.wfile.write(response.content)
29+
self.wfile.flush()
30+
31+
def do_POST(self):
32+
print(f"POST Path: {self.path}")
33+
for key, value in self.headers.items():
34+
print(f"{key}: {value}")
35+
self.send_response(200)
36+
self.send_header("Content-type", "text/html")
37+
self.end_headers()
38+
self.wfile.write(b"test post")
39+
40+
41+
def run(host: str, port: int):
42+
listen_address = (host, port)
43+
httpd = ThreadingHTTPServer(listen_address, HTTPRequestProxy)
44+
print(f"Listening on {host}:{port}")
45+
httpd.serve_forever()
46+
47+
48+
if __name__ == "__main__":
49+
run("0.0.0.0", 5000)

0 commit comments

Comments
 (0)