Skip to content

Instantly share code, notes, and snippets.

@codemation
Created March 4, 2021 08:54
Show Gist options
  • Save codemation/d21a9bd00ebfb15232483273bf8fd988 to your computer and use it in GitHub Desktop.
Save codemation/d21a9bd00ebfb15232483273bf8fd988 to your computer and use it in GitHub Desktop.
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def change_path(request: Request, call_next):
# get mutable copy of request
request = dict(request)
# extract host from headers
_, host = request['headers'][0]
host = host.decode()
if ':' in host:
host = host.split(':')[0]
# route based on host
if host == 'sub-a.domain.com':
request['path'] = f"/router1{request['path']}"
if host == 'sub-b.domain.com':
request['path'] = f"/router2{request['path']}"
request = Request(request)
response = await call_next(request)
return response
# not separate routers, but you get the point
@app.get('/router1/{name}')
async def get_name(name: str):
return {'router1': name}
@app.get('/router2/{name}')
async def get_name(name: str):
return {'router2': name}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment