Repository navigation
Expand file tree
/
Copy pathserve.py
More file actions
182 lines (148 loc) · 6.53 KB
/
Copy pathserve.py
File metadata and controls
182 lines (148 loc) · 6.53 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env python3
"""
serve — Local HTTP server with CORS, file upload, and custom headers.
Like 'python -m http.server' but actually useful for development.
Includes CORS headers by default (the #1 missing feature).
Usage:
py serve.py # Serve current dir on 8000
py serve.py 3000 # Custom port
py serve.py -d ./build # Serve specific directory
py serve.py --no-cors # Disable CORS headers
py serve.py --upload # Enable file upload via POST
py serve.py --spa # SPA mode (fallback to index.html)
py serve.py --header "X-Custom: val" # Add custom response header
py serve.py --open # Auto-open browser
"""
import argparse
import html
import os
import sys
import urllib.parse
import webbrowser
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pathlib import Path
from functools import partial
import io
class DevHTTPRequestHandler(SimpleHTTPRequestHandler):
"""Enhanced HTTP handler with CORS, upload, SPA support."""
cors_enabled = True
upload_enabled = False
spa_mode = False
custom_headers = {}
def end_headers(self):
"""Add CORS and custom headers to every response."""
if self.cors_enabled:
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
self.send_header("Access-Control-Allow-Headers", "*")
self.send_header("Access-Control-Max-Age", "86400")
# Disable caching for dev
self.send_header("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
for key, value in self.custom_headers.items():
self.send_header(key, value)
super().end_headers()
def do_OPTIONS(self):
"""Handle CORS preflight."""
self.send_response(204)
self.end_headers()
def do_POST(self):
"""Handle file upload."""
if not self.upload_enabled:
self.send_response(405)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"Upload disabled. Use --upload flag.")
return
content_length = int(self.headers.get("Content-Length", 0))
if content_length == 0:
self.send_response(400)
self.end_headers()
self.wfile.write(b"No content")
return
# Simple upload: save body as file
filename = self.headers.get("X-Filename", "upload")
filename = os.path.basename(filename) # prevent path traversal
filepath = Path(self.directory) / filename
body = self.rfile.read(content_length)
filepath.write_bytes(body)
self.send_response(201)
self.send_header("Content-Type", "application/json")
self.end_headers()
response = f'{{"status":"ok","file":"{filename}","size":{len(body)}}}'
self.wfile.write(response.encode())
self.log_message("Uploaded: %s (%d bytes)", filename, len(body))
def do_GET(self):
"""Handle GET with SPA fallback."""
if self.spa_mode:
path = self.translate_path(self.path)
if not os.path.exists(path) and not os.path.splitext(self.path)[1]:
# No file extension and doesn't exist -> serve index.html
self.path = "/index.html"
super().do_GET()
def log_message(self, format, *args):
"""Colored log output."""
method = args[0] if args else ""
status = args[1] if len(args) > 1 else ""
# Color by status code
if isinstance(status, str) and status.startswith("2"):
color = "\033[32m" # green
elif isinstance(status, str) and status.startswith("3"):
color = "\033[33m" # yellow
elif isinstance(status, str) and (status.startswith("4") or status.startswith("5")):
color = "\033[31m" # red
else:
color = ""
reset = "\033[0m" if color else ""
sys.stderr.write(f" {color}{format % args}{reset}\n")
def main():
parser = argparse.ArgumentParser(
description="serve -- local dev server with CORS, upload, and SPA support"
)
parser.add_argument("port", nargs="?", type=int, default=8000, help="Port (default: 8000)")
parser.add_argument("-d", "--directory", default=".", help="Directory to serve")
parser.add_argument("--no-cors", action="store_true", help="Disable CORS headers")
parser.add_argument("--upload", action="store_true", help="Enable file upload via POST")
parser.add_argument("--spa", action="store_true", help="SPA mode (fallback to index.html)")
parser.add_argument("--header", action="append", default=[], help="Custom header (Key: Value)")
parser.add_argument("--open", action="store_true", help="Auto-open browser")
parser.add_argument("--bind", default="127.0.0.1", help="Bind address (default: 127.0.0.1)")
args = parser.parse_args()
directory = os.path.abspath(args.directory)
if not os.path.isdir(directory):
print(f"Error: {directory} is not a directory", file=sys.stderr)
sys.exit(1)
# Configure handler
DevHTTPRequestHandler.cors_enabled = not args.no_cors
DevHTTPRequestHandler.upload_enabled = args.upload
DevHTTPRequestHandler.spa_mode = args.spa
for h in args.header:
if ":" in h:
key, _, value = h.partition(":")
DevHTTPRequestHandler.custom_headers[key.strip()] = value.strip()
handler = partial(DevHTTPRequestHandler, directory=directory)
try:
server = HTTPServer((args.bind, args.port), handler)
except OSError as e:
if "Address already in use" in str(e) or "10048" in str(e):
print(f"Error: port {args.port} is already in use. Try: py portman.py {args.port}", file=sys.stderr)
sys.exit(1)
raise
url = f"http://{args.bind}:{args.port}"
features = []
if not args.no_cors: features.append("CORS")
if args.upload: features.append("Upload")
if args.spa: features.append("SPA")
feat_str = f" [{', '.join(features)}]" if features else ""
print(f"\n serve -- Local dev server{feat_str}")
print(f" Serving: {directory}")
print(f" URL: {url}")
print(f" Press Ctrl+C to stop\n")
if args.open:
webbrowser.open(url)
try:
server.serve_forever()
except KeyboardInterrupt:
print("\n Server stopped.")
server.server_close()
if __name__ == "__main__":
main()