|
|
|
@ -12,9 +12,9 @@ import aiohttp
|
|
|
|
|
import contextlib |
|
|
|
|
import contextvars |
|
|
|
|
from yarl import URL |
|
|
|
|
from aiohttp import web |
|
|
|
|
import pytomlpp as toml |
|
|
|
|
from utils import build_dprint_factory, ContextVar |
|
|
|
|
from aiohttp import web |
|
|
|
|
from utils import build_dprint_factory, ContextVar, MultiReplacer |
|
|
|
|
|
|
|
|
|
def load_config(): |
|
|
|
|
with open(sys.argv[1] if len(sys.argv) > 1 else 'config.toml') as f: |
|
|
|
@ -22,11 +22,14 @@ def load_config():
|
|
|
|
|
|
|
|
|
|
for host in config['hosts'].values(): |
|
|
|
|
if not host.setdefault('replace', True): continue |
|
|
|
|
host['pattern_decoded'] = host['pattern'] |
|
|
|
|
host['pattern'] = re.compile(host['pattern'].encode()) |
|
|
|
|
host['repl_decoded'] = host['repl'] |
|
|
|
|
host['repl'] = host['repl'].encode() |
|
|
|
|
host['mime_types'] = frozenset(host.get('mime_types', ())) |
|
|
|
|
|
|
|
|
|
host['replacer'] = MultiReplacer({ |
|
|
|
|
replacement['pattern'].encode(): replacement['repl'].encode() |
|
|
|
|
for replacement |
|
|
|
|
in host['replacements'] |
|
|
|
|
}) |
|
|
|
|
|
|
|
|
|
try: |
|
|
|
|
host['excluded_routes'].sort(key=len, reverse=True) |
|
|
|
|
except KeyError: |
|
|
|
@ -99,13 +102,13 @@ async def _handler(request):
|
|
|
|
|
) |
|
|
|
|
return await proxy_passthrough(upstream_resp, resp) |
|
|
|
|
|
|
|
|
|
dprint()('replacing', repr(hconfig['pattern_decoded']), 'with', repr(hconfig['repl_decoded'])) |
|
|
|
|
dprint()('replacing', hconfig['replacer'].replacements) |
|
|
|
|
return await proxy_replace(hconfig, upstream_resp, resp) |
|
|
|
|
|
|
|
|
|
async def proxy_replace(hconfig, upstream_resp, resp): |
|
|
|
|
# iter_lines when |
|
|
|
|
while (line := await upstream_resp.content.readline()): |
|
|
|
|
await resp.write(hconfig['pattern'].sub(hconfig['repl'], line)) |
|
|
|
|
await resp.write(hconfig['replacer'].replace(line)) |
|
|
|
|
|
|
|
|
|
return await finalize_resp(resp) |
|
|
|
|
|
|
|
|
|