Skip to content

Instantly share code, notes, and snippets.

@cbare
Created May 6, 2022 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbare/82bac507b46a6d48ec380421c554b055 to your computer and use it in GitHub Desktop.
Save cbare/82bac507b46a6d48ec380421c554b055 to your computer and use it in GitHub Desktop.
"""
A simple HTTPS server
Generate cert and key with:
```sh
openssl req -newkey rsa:4096 -x509 -sha256 -days 3650 -nodes -subj '/CN=localhost' -out ./ssl/cert.pem -keyout ./ssl/key.pem
```
Test with httpie:
```sh
http -v --verify no https://localhost:42999/hello
```
"""
import http.server
import ssl
PORT = 42999
def extract_query_params(path):
params = {}
if "?" in path:
path, query_string = path.split("?")
for kvp in query_string.split("&"):
k,v = kvp.split("=")
params[k] = v
return path, params
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
client_host, client_port = self.client_address
path_part, params = extract_query_params(self.path)
print({
"path": path_part,
"client": client_host,
"port": client_port,
"params": params
})
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write("Hello, Dammit!".encode("utf-8"))
httpd = http.server.HTTPServer(("localhost", PORT), Handler, False)
httpd.timeout = 60.0
ssl_context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain(
certfile="ssl/cert.pem",
keyfile="ssl/key.pem",
)
httpd.socket = ssl_context.wrap_socket(httpd.socket, server_side=True)
httpd.server_bind()
httpd.server_activate()
httpd.serve_forever()
@cbare
Copy link
Author

cbare commented May 7, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment