support excluding specific routes

This commit is contained in:
Kay Faraday 2021-09-08 03:28:49 +00:00
parent 50c22cd5b9
commit 72de283a8d
2 changed files with 20 additions and 9 deletions

27
app.py
View File

@ -16,17 +16,22 @@ from aiohttp import web
import pytomlpp as toml
from utils import build_dprint, ContextVar
with open(sys.argv[1] if len(sys.argv) > 1 else 'config.toml') as f:
config = toml.load(f)
def load_config():
with open(sys.argv[1] if len(sys.argv) > 1 else 'config.toml') as f:
config = toml.load(f)
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', ()))
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('excluded_routes', ()))
host['excluded_routes'].sort(key=len, reverse=True)
return config
config = load_config()
dprint = build_dprint(config.get('debug'))
http = ContextVar('http')
@ -52,6 +57,10 @@ async def handler(request):
if not hconfig['replace']:
print('Not replacing for this host')
return await proxy_passthrough(upstream_resp, resp)
for excluded_route in hconfig['excluded_routes']:
if request.path.startswith(excluded_route):
print('Not replacing for', excluded_route)
return await proxy_passthrough(upstream_resp, resp)
if hconfig['mime_types'] and upstream_resp.content_type not in hconfig['mime_types']:
print('Not configured to replace for MIME type', upstream_resp.content_type)
return await proxy_passthrough(upstream_resp, resp)

View File

@ -15,6 +15,8 @@ pattern = 'foo'
repl = 'bar'
# which mime types to replace for. defaults to all mime types.
mime_types = ['text/html', 'application/json', 'application/activity+json', 'application/ld+json']
# path prefixes not to replace for. these are applied in descending order of length.
excluded_routes = ['/.well-known/', '/user/']
# just pass through site2.example unmodified
[hosts."site2.example"]