Skip to content

Instantly share code, notes, and snippets.

@tuxfight3r
Last active March 9, 2022 10:23
Show Gist options
  • Save tuxfight3r/02be52689e582a14083548a1e4de9851 to your computer and use it in GitHub Desktop.
Save tuxfight3r/02be52689e582a14083548a1e4de9851 to your computer and use it in GitHub Desktop.
python3 HTTP Echo Server with directory browsing
#!/usr/bin/env python3
# Author: Mohan Balasundaram
# Date: 02/05/2019
# Purpose: HTTP Echo server with directory browsing
# To run a http server and return all request headers in / path
# and to allow directory browsing in any other path prefix
from http.server import BaseHTTPRequestHandler, SimpleHTTPRequestHandler
import urllib.parse
class GetHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path = urllib.parse.urlparse(self.path)
message_parts = [
'CLIENT VALUES:',
'client_address=%s (%s)' % (self.client_address,
self.address_string()),
'command=%s' % self.command,
'path=%s' % self.path,
'real path=%s' % parsed_path.path,
'query=%s' % parsed_path.query,
'request_version=%s' % self.request_version,
'',
'SERVER VALUES:',
'server_version=%s' % self.server_version,
'sys_version=%s' % self.sys_version,
'protocol_version=%s' % self.protocol_version,
'',
'HEADERS RECEIVED:',
]
for name, value in sorted(self.headers.items()):
message_parts.append('%s=%s' % (name, value.rstrip()))
message_parts.append('')
message = '\r\n'.join(message_parts)
self.send_response(200)
self.end_headers()
self.wfile.write(message.encode('utf-8'))
return
class RouteHandler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
return GetHandler.do_GET(self)
else:
super(RouteHandler, self).do_GET()
if __name__ == '__main__':
from http.server import HTTPServer
server = HTTPServer(('0.0.0.0', 8080), RouteHandler)
print('Starting server, use <Ctrl-C> to stop')
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment