I can make the Webserver DAT serve a simple webpage (including images, css, and JS) with onHTTPRequest
as follows:
import os
from urllib.parse import urlparse
web_root = "WebRoot" # location of HTML files relative to .toe
def onHTTPRequest(webServerDAT, request, response):
#convert request[uri] into local file path
url_parsed = urlparse(request['uri'])
path = url_parsed.path.lstrip('/').replace("/", os.path.sep)
path = os.path.join(web_root, path)
response['statusCode'] = 200
response['statusReason'] = 'OK'
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()
return response
(this is simplified for the sake of the forum. full version here)
But letās say Iām loading http://localhost:9980/foo/index.html
from my trusty local browser.
Here is [WebRoot]/foo/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
Hello, World!
</body>
</html>
In the first request that hits onHTTPRequest, request[āuriā] is /foo/index.html. Everything works great.
But the second request that hits onHTTPRequest is for /style.cs
s, and in this example, that is incorrect. It should request /foo/style.css
because there is no leading slash in the tag in the HTML.
Iāve examined the request dict that onHTTPRequest receives, and I canāt find anything that would allow me to fix this in Python. I suppose, at the very least, Iād need a way to determine that the request is relative (not provided), and the Referrer (is provided).
Of course the short-term fix is just to make all of my HTML links absolute paths. But it just seems like this is something that the Webserver DAT should be able to handle.
Am I missing something here?