Created
November 4, 2016 18:36
-
-
Save kainam00/39c8d5876027e38f112d6f07c785bb56 to your computer and use it in GitHub Desktop.
A simple HTTP server designed to be slow. Useful for testing LB timeouts and such.
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 python | |
# Includes | |
import getopt | |
import sys | |
import os.path | |
import subprocess | |
import BaseHTTPServer | |
import SocketServer | |
import time | |
######## Predefined variables ######### | |
helpstring = """Usage: {scriptname} args... | |
Where args are: | |
-h, --help | |
Show help | |
-p PORTNUMBER | |
Port number to run on | |
-d delay-in-seconds | |
How long to wait before responding | |
""" | |
helpstring = helpstring.format(scriptname=sys.argv[0]) | |
def beSlow(seconds): | |
time.sleep(float(seconds)) | |
######## Functions and classes ######### | |
class SlowserverRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): | |
def do_GET(s): | |
if s.path == "/slow": | |
# Check status | |
# Assume fail | |
code = 200 | |
status = "" | |
# Be slow for a while | |
beSlow(seconds) | |
s.send_response(200) | |
s.send_header("Content-type", "text/html") | |
s.end_headers() | |
s.wfile.write("I'm a slow response LOL\n") | |
else: | |
s.send_response(200) | |
s.send_header("Content-type", "text/html") | |
s.end_headers() | |
s.wfile.write("slowserver - reporting for duty. Slowly...\n") | |
# Parse args | |
try: | |
options, remainder = getopt.getopt(sys.argv[1:], "hp:d:", ['help']) | |
except: | |
print("Invalid args. Use -h or --help for help.") | |
raise | |
sys.exit(1) | |
for opt, arg in options: | |
if opt in ('-h', '--help'): | |
print helpstring | |
sys.exit(0) | |
elif opt in ('-p'): | |
HTTPPORT = int(arg) | |
elif opt in ('-d'): | |
seconds = arg | |
# Start HTTP service | |
server_class=BaseHTTPServer.HTTPServer | |
handler_class=SlowserverRequestHandler | |
server_address = ('', HTTPPORT) | |
httpd = server_class(server_address, handler_class) | |
try: | |
httpd.serve_forever() | |
except KeyboardInterrupt: | |
pass | |
httpd.server_close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks Dmitriy, that was useful. Here's a version adapted for Python 3: