7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

すべての HTTP リクエストを右から左へ受け流す Web サーバ

Posted at

チャラチャッチャッチャラッチャ~♪1

届いたすべての HTTP リクエストを何も手を加えずに右から左へ受け流すだけの Web サーバを Python + aiohttp で作った。誰得?

main.py
from os import getenv

from aiohttp import ClientSession, web

UPSTREAM = getenv("UPSTREAM")
if UPSTREAM is None:
    raise Exception("UPSTREAM is required")


async def handler(request: web.Request):
    headers = {**request.headers}
    del headers["Host"]
    async with ClientSession() as session:
        async with session.request(
            request.method,
            f"{UPSTREAM}{request.path_qs}",
            headers=headers,
            data=await request.read(),
        ) as upstream_response:
            response = web.StreamResponse(
                status=upstream_response.status,
                headers=upstream_response.headers,
            )
            await response.prepare(request)
            async for chunk in upstream_response.content.iter_chunked(1024):
                await response.write(chunk)
    return response


app = web.Application()
app.add_routes([web.route("*", "/{_:.*}", handler)])

if __name__ == "__main__":
    web.run_app(app)
$ UPSTREAM=https://api.example.com/v1 python main.py

単に HTTP リクエストを流すだけであれば Nginx を使うなどしてリバースプロキシすればよいのだが、Python スクリプトとして書いておくことで通信内容を読み取ったり手を加えたりすることができて便利。

  1. ムーディ勝山 - 右から来たものを左へ受け流すの歌

7
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?