Created
May 6, 2022 03:40
-
-
Save cbare/82bac507b46a6d48ec380421c554b055 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
see also: https://gist.github.com/gh640/3c54c2eb5a8af889e3ab5f49cc4befc6