Last active
February 19, 2020 08:36
-
-
Save ssledz/951e2e845574a2ba81d574e1bedbb2f0 to your computer and use it in GitHub Desktop.
Very simple HTTP server in python.
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 | |
""" | |
Very simple HTTP server in python. | |
Usage:: | |
./dummy-web-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 BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer | |
import SocketServer | |
class S(BaseHTTPRequestHandler): | |
def print_req_headers(self): | |
print("Headers:\n%s" % self.headers) | |
def print_req_body(self): | |
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data | |
post_data = self.rfile.read(content_length) # <--- Gets the data itself | |
print("body: %s" % post_data) | |
def _set_headers(self): | |
self.send_response(200) | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
def do_GET(self): | |
self.print_req_headers() | |
self._set_headers() | |
self.wfile.write("<html><body><h1>Hi!</h1></body></html>") | |
def do_HEAD(self): | |
self.print_req_headers() | |
self._set_headers() | |
def do_PUT(self): | |
self.do_POST() | |
def do_POST(self): | |
self.print_req_headers() | |
self.print_req_body() | |
self._set_headers() | |
self.wfile.write("<html><body><h1>Welcome</h1></body></html>") | |
def run(server_class=HTTPServer, handler_class=S, port=80): | |
server_address = ('', port) | |
httpd = server_class(server_address, handler_class) | |
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