Skip to content

Instantly share code, notes, and snippets.

@brendanmaguire
Created November 21, 2017 16:42
Show Gist options
  • Save brendanmaguire/71941dfa4b3f4b0f7088da9e01d7c04f to your computer and use it in GitHub Desktop.
Save brendanmaguire/71941dfa4b3f4b0f7088da9e01d7c04f to your computer and use it in GitHub Desktop.
A simple dummy server to print the request to stdout
#!/usr/bin/env python3
"""
Very simple HTTP server in python.
Usage::
./dummyserve [<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
"""
import time
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
import argh
class S(BaseHTTPRequestHandler):
def handle(self, *args, **kwargs):
if DELAY:
print("Delaying")
time.sleep(DELAY)
return BaseHTTPRequestHandler.handle(self, *args, **kwargs)
def _set_headers(self, status=200):
self.send_response(status)
self.send_header('Content-type', 'text/html')
self.end_headers()
def _echo(self):
print("Headers:\n%s" % self.headers)
body = self.rfile.read(int(self.headers.get('content-length') or 0))
try:
body = json.loads(body.decode("utf-8", "ignore"))
body_str = json.dumps(body, indent=4, sort_keys=True)
except:
body_str = body
print("Body:\n%s" % body_str)
print("---\n")
def do_GET(self):
self._set_headers()
self._echo()
self.wfile.write(
"<html><body><h1>GET!</h1></body></html>".encode('UTF-8')
)
def do_HEAD(self):
self._set_headers()
self._echo()
def do_POST(self):
# Doesn't do anything with posted data
self._set_headers(201)
self._echo()
self.wfile.write(
"<html><body><h1>POST!</h1></body></html>".encode('UTF-8')
)
def do_PUT(self):
# Doesn't do anything with put data
self._set_headers(201)
self._echo()
self.wfile.write(
"<html><body><h1>PUT!</h1></body></html>".encode('UTF-8')
)
DELAY = 0
def run(port=80, delay=0):
server_address = ('', port)
# This is obviously horrible but can't be arsed doing it correctly right now
global DELAY
DELAY = delay
httpd = HTTPServer(server_address, S)
print('Starting httpd...')
httpd.serve_forever()
if __name__ == "__main__":
argh.dispatch_command(run)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment