-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy_server.py
More file actions
67 lines (57 loc) · 2.64 KB
/
proxy_server.py
File metadata and controls
67 lines (57 loc) · 2.64 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import http.server
import socketserver
import urllib.request
import json
PORT = 9999
DEVAUDIT_API = "http://127.0.0.1:8001"
CRM_API = "http://127.0.0.1:8888"
class DevAuditProxy(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path.startswith('/api-crm/'):
return self.proxy_request('GET', CRM_API, '/api-crm')
elif self.path.startswith('/api/'):
return self.proxy_request('GET', DEVAUDIT_API, '')
else:
if self.path == '/' or self.path == '' or self.path == '/index.html':
self.path = '/landing_preview.html'
return super().do_GET()
def do_POST(self):
if self.path.startswith('/api-crm/'):
return self.proxy_request('POST', CRM_API, '/api-crm')
elif self.path.startswith('/api/'):
return self.proxy_request('POST', DEVAUDIT_API, '')
else:
self.send_error(405)
def proxy_request(self, method, target_api, path_prefix):
# Translate /api-crm/leads to /api/leads for the CRM backend
if path_prefix == '/api-crm':
target_url = f"{target_api}/api{self.path[len(path_prefix):]}"
else:
target_url = f"{target_api}{self.path}"
print(f"[Proxy] {method} {self.path} -> {target_url}")
try:
content_length = int(self.headers.get('Content-Length', 0))
body = self.rfile.read(content_length) if content_length > 0 else None
req = urllib.request.Request(target_url, data=body, method=method)
for key, value in self.headers.items():
if key.lower() not in ('host', 'content-length', 'connection'):
req.add_header(key, value)
with urllib.request.urlopen(req) as resp:
self.send_response(resp.status)
for key, value in resp.getheaders():
if key.lower() not in ('content-length', 'transfer-encoding', 'connection'):
self.send_header(key, value)
data = resp.read()
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
except Exception as e:
print(f"[Proxy] Error: {e}")
self.send_response(500)
self.end_headers()
self.wfile.write(str(e).encode())
if __name__ == "__main__":
socketserver.TCPServer.allow_reuse_address = True
with socketserver.TCPServer(("", PORT), DevAuditProxy) as httpd:
print(f"Unified Proxy serving at port {PORT}")
httpd.serve_forever()