Skip to content

Instantly share code, notes, and snippets.

@jeffcrouse
Last active July 16, 2024 14:53
Show Gist options
  • Save jeffcrouse/32c1df6153c7c04c3ad66f514276d944 to your computer and use it in GitHub Desktop.
Save jeffcrouse/32c1df6153c7c04c3ad66f514276d944 to your computer and use it in GitHub Desktop.
Simple HTML webserver callback
import os
import mimetypes
from urllib.parse import urlparse
mimetypes.init()
web_root = "WebRoot"
def onHTTPRequest(webServerDAT, request, response):
url_parsed = urlparse(request['uri']) # parse the incoming request uri
path = url_parsed.path.lstrip('/') # strip the leading slash off of the path
path = path.replace("/", os.path.sep) # For Windows: convert slashes to OS-appropraite path separator
path = os.path.join(web_root, path) # prefix with the dir where the HTML lives
if os.path.isdir(path):
path = os.path.join(path, "index.html")
# Does this file exist on the system?
if os.path.exists(path):
response['statusCode'] = 200
response['statusReason'] = 'OK'
# Certain files (like SVG) require Content-Type
type = mimetypes.guess_type(request['uri'])
if type[0] is not None:
response["Content-Type"] = type[0]
# Lazy way of determining whether we have binary text file
try:
with open(path, mode='r', encoding='utf-8') as file:
response['data'] = file.read()
except UnicodeDecodeError:
with open(path, mode='rb') as file:
response['data'] = file.read()
else:
response['statusCode'] = 404
response['statusReason'] = 'NOT FOUND'
response['data'] = "File Not Found: " + path
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment