gets X-Forwarded-Prefix from requests and adds it to index.html

This commit is contained in:
Mose Müller 2024-09-26 21:08:48 +02:00
parent ff301f225c
commit fdfdef5837

View File

@ -6,6 +6,7 @@ from typing import Any
import aiohttp.web
import aiohttp_middlewares.cors
import anyio
from pydase.config import ServiceConfig, WebServerConfig
from pydase.data_service.data_service_observer import DataServiceObserver
@ -99,7 +100,32 @@ class WebServer:
self._loop = asyncio.get_running_loop()
self._sio = setup_sio_server(self.observer, self.enable_cors, self._loop)
async def index(request: aiohttp.web.Request) -> aiohttp.web.FileResponse:
async def index(
request: aiohttp.web.Request,
) -> aiohttp.web.Response | aiohttp.web.FileResponse:
# Read the X-Forwarded-Prefix header from the request
forwarded_prefix = request.headers.get("X-Forwarded-Prefix", "")
if forwarded_prefix != "":
# Read the index.html file
index_file_path = self.frontend_src / "index.html"
async with await anyio.open_file(index_file_path) as f:
html_content = await f.read()
# Inject the forwarded prefix into the HTML
modified_html = html_content.replace(
'window.__FORWARDED_PREFIX__ = "";',
f'window.__FORWARDED_PREFIX__ = "{forwarded_prefix}";',
)
modified_html = modified_html.replace(
"/assets/",
f"{forwarded_prefix}/assets/",
)
return aiohttp.web.Response(
text=modified_html, content_type="text/html"
)
return aiohttp.web.FileResponse(self.frontend_src / "index.html")
app = aiohttp.web.Application()