Created
June 8, 2020 21:46
-
-
Save raylu/d4a1b0bc38dc30528bda70188d9c50eb to your computer and use it in GitHub Desktop.
starter code for httpd on https://www.raylu.net/systems/
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
#!/usr/bin/env python3 | |
# so you want to write an HTTP server? | |
# | |
# 1. run `curl --trace-ascii http.log httpbin.org/html` and read http.log | |
# 2. run this code and try it in curl and your browser | |
# 3. good luck! | |
# | |
# here are some extra features to add: | |
# | |
# 1. parse the request URI and serve up files from some directory | |
# (so `curl localhost:1234/x/y` returns file y in dir x) | |
# 2. refactor your code | |
# 3. send Content-Length | |
# 4. refactor your code | |
# 5. implement threading | |
# 6. refactor your code | |
# 7. handle caching | |
# 8. refactor your code | |
# 9. handle large files (larger than your RAM) | |
# 10. refactor your code | |
# 11. get rid of threading and implement async I/O | |
import socket | |
def main(): | |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: | |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
sock.bind(('127.0.0.1', 8000)) | |
sock.listen(1) | |
conn, addr = sock.accept() | |
print('connected by', addr) | |
with conn: | |
data = conn.recv(4096) | |
print(data) | |
conn.send('HTTP/1.0 200 OK\nContent-Type: text/html; charset=utf-8\nContent-Length: 55\n\n'.encode('ascii')) | |
conn.send('<!DOCTYPE html><html><body><h1>hello</h1></body></html>'.encode('utf-8')) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment