Last active
February 15, 2023 10:11
-
-
Save xxxzc/7bc774e28530222308b722223fc641cd to your computer and use it in GitHub Desktop.
Simple sanic reverse proxy using aiohttp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Inspired by https://gist.github.com/ashleysommer/477d2ee24f0421e56986a6f758397dcb | |
# Used in https://github.com/xxxzc/asar/blob/c92c646fae3c4b67fa4f81cee034b390961cb8b6/app.py#L22 | |
# Created by xxxzc | |
from sanic import Request, HTTPResponse | |
from aiohttp import ClientSession, ClientResponse | |
async def reverse_proxy(r: Request, base: str, path: str) -> HTTPResponse: | |
"""Reverse proxy for base+path""" | |
async with ClientSession() as session: | |
http_method = getattr(session, r.method.lower()) # HTTP Method | |
async with http_method(base+path, headers=r.headers, | |
params=r.args, json=r.json) as resp: | |
resp: ClientResponse | |
response = await r.respond(content_type=resp.content_type, | |
status=resp.status, headers=resp.headers) | |
async for data in resp.content.iter_any(): | |
await response.send(data) | |
await response.eof() | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment