support regexes

This commit is contained in:
Kay Faraday 2021-09-08 02:40:44 +00:00
parent 00c30d2af0
commit 44f956c1a3
2 changed files with 4 additions and 2 deletions

5
app.py
View File

@ -3,6 +3,7 @@
import io
import os
import re
import sys
import utils
import random
@ -21,7 +22,7 @@ with open(sys.argv[1] if len(sys.argv) > 1 else 'config.toml') as f:
for host in config['hosts'].values():
if not host.get('replace', True): continue
host['pattern_decoded'] = host['pattern']
host['pattern'] = host['pattern'].encode()
host['pattern'] = re.compile(host['pattern'].encode())
host['repl_decoded'] = host['repl']
host['repl'] = host['repl'].encode()
@ -51,7 +52,7 @@ async def handler(request):
# iter_lines when
print('replacing', repr(hconfig['pattern_decoded']), 'with', repr(hconfig['repl_decoded']))
while (line := await upstream_resp.content.readline()):
await resp.write(line.replace(hconfig['pattern'], hconfig['repl']))
await resp.write(hconfig['pattern'].sub(hconfig['repl'], line))
else:
print('not replacing')
async for chunk in upstream_resp.content.iter_chunked(io.DEFAULT_BUFFER_SIZE):

View File

@ -10,6 +10,7 @@ debug = True
# replace foo with bar for site1.example
[hosts."site1.example"]
upstream = 'http://localhost:3001'
# these can be regexes
pattern = 'foo'
repl = 'bar'