Logo

index : blog

---

  • summary
  • about
  • tree
  • log
  • branches
<< path: root/public/blog.git/html/dev/server.py blob: dd88a8a047c95336149a48a14fffcfa7c7be9118 [raw] [clear marker]

        
0#!/bin/python
1from http.server import HTTPServer, SimpleHTTPRequestHandler
2from http.client import HTTPConnection
3from urllib.parse import urlparse, parse_qs
4from functools import partial
5import os
6
7
8# This kinda mimics the behavior of my nginx config.
9# Do not use it in prod!
10
11LOCALHOST = "127.0.0.1"
12SEARCH_SERVER_PORT = 8081
13WEB_SERVER_PORT = 8000
14ROOT_DIR = "www/"
15
16
17class RewriteHandler(SimpleHTTPRequestHandler):
18 def do_GET(self):
19 parsed = urlparse(self.path)
20 query = parse_qs(parsed.query)
21 path = parsed.path
22
23 if 'q' in query:
24 self.forward_to_search_server(self.path)
25 return
26 elif 'ts' in query:
27 ts_value = query['ts'][0]
28 new_path = f"posts/{ts_value}.html"
29 self.path = new_path
30 elif parsed.path == "/rss":
31 self.path = "/ptrace.dev.rss"
32 else:
33 file_path = self.translate_path(path)
34 if not os.path.exists(file_path):
35 file_path_html = self.translate_path(path + ".html")
36 if os.path.exists(file_path_html):
37 self.path = path + ".html"
38
39 return super().do_GET()
40
41 def handle(self):
42 try:
43 super().handle()
44 except BrokenPipeError:
45 pass
46
47 def send_error(self, code, message=None, explain=None):
48 try:
49 super().send_error(code, message, explain)
50 except BrokenPipeError:
51 pass
52
53 def forward_to_search_server(self, path):
54 try:
55 conn = HTTPConnection(LOCALHOST, SEARCH_SERVER_PORT)
56 conn.request("GET", path, headers={"Host": f"{LOCALHOST}:8000"})
57 resp = conn.getresponse()
58
59 self.send_response(resp.status)
60 for key, value in resp.getheaders():
61 if key.lower() not in ("transfer-encoding", "connection"):
62 self.send_header(key, value)
63 self.end_headers()
64
65 self.wfile.write(resp.read())
66 except ConnectionRefusedError:
67 self.send_error(502, "Search server unavailable")
68 finally:
69 conn.close()
70
71
72if __name__ == "__main__":
73 handler = partial(RewriteHandler, directory=ROOT_DIR)
74 server = HTTPServer((LOCALHOST, WEB_SERVER_PORT), handler)
75
76 try:
77 print(f"Serving {ROOT_DIR} on http://localhost:{WEB_SERVER_PORT}")
78 print("DO NOT USE IT IN PROD!")
79 print("DO NOT USE IT IN PROD!")
80 print("DO NOT USE IT IN PROD!")
81 print("----------------------")
82 server.serve_forever()
83 except KeyboardInterrupt:
84 print("\nStopping server...")
85 server.shutdown()
86 server.server_close()
87
88
Copyright 2026  E766CB298A6D1E64 | Git-Thing heavily inspired by cgit