Skip to content

Instantly share code, notes, and snippets.

@Bnux256
Created January 9, 2022 07:10
Show Gist options
  • Save Bnux256/ae8dcbcd097d868476e7f5d98fbe3fb4 to your computer and use it in GitHub Desktop.
Save Bnux256/ae8dcbcd097d868476e7f5d98fbe3fb4 to your computer and use it in GitHub Desktop.
Simple HTTP GET Server - Python
import socket
import os
import mimetypes
import sys
import pathlib # using pathlib to create a universal object that can be used in unix or windows alike
HOST = '127.0.0.1'
PORT = 8888
class HTTPServ:
def __init__(self, host = '127.0.0.1', port = 80):
self.host = host
self.port = port
def startServ(self):
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((self.host, self.port)) #
s.listen()
while True:
# waiting for connection
conn, addr = s.accept()
with conn:
print('Connected by', addr)
# get client request
request = conn.recv(1024)
response = self.handle_request(request)
conn.sendall(response)
except PermissionError:
print('Permission Error, check firewall.')
sys.exit(1)
except OSError:
print('Address already in use. Exiting.')
sys.exit(1)
def handle_request(self, request):
# handling request types
headers = request.decode().split('/n')
if headers[0].startswith('GET'):
return self.handle_GET(headers)
else:
return b'HTTP/1.1 200 OK\n\nDidn\'t recieve GET request'
def handle_GET(self, headers):
# calling appropriate methods for different GET request type
filename = headers[0].split()[1]
if filename == '/': # if no adders was given we open index.html
filename = '/index.html'
return self.get_request(filename)
def get_request(self, filename):
# parsing regular http request
try:
filename = filename[0].strip('/') + filename[1:] # remove slash from URL
with pathlib.Path(filename).open(mode = 'rb') as file:
response_line = b'HTTP/1.1 200 OK'
content = file.read()
headers = b'Content-Type: ' + mimetypes.guess_type(filename)[
0].encode() # if nothing is found, just send `text/html`
blank_line = b'\r\n'
response = b''.join([response_line, blank_line, headers, blank_line, blank_line, content])
except FileNotFoundError:
response = b'HTTP/1.0 404 NOT FOUND\n\nFile Not Found'
return response
if __name__ == '__main__':
server = HTTPServ(HOST, PORT)
server.startServ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment