Skip to content

Instantly share code, notes, and snippets.

@wulymammoth
Created May 20, 2019 00:36
Show Gist options
  • Save wulymammoth/96528540fea31a933dce2b91c74f2696 to your computer and use it in GitHub Desktop.
Save wulymammoth/96528540fea31a933dce2b91c74f2696 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Very simple HTTP server in python.
Usage::
./simple_server.py [<port>]
Send a GET request::
curl http://localhost
Send a HEAD request::
curl -I http://localhost
Send a POST request::
curl -d "foo=bar&bin=baz" http://localhost
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
class RequestHandler(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("foobar", "utf-8"))
def do_HEAD(self):
self._set_headers()
def do_POST(self):
# Doesn't do anything with posted data
self._set_headers()
self.wfile.write("<html><body><h1>POST!</h1></body></html>")
def run(server=HTTPServer, request_handler=RequestHandler, port=3000):
server_address = ('', port)
httpd = server(server_address, request_handler)
print('Starting httpd...')
httpd.serve_forever()
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment