Skip to content

Commit

Permalink
Fix Host based routing to check path too
Browse files Browse the repository at this point in the history
  • Loading branch information
aminalaee committed Sep 6, 2023
1 parent f1ad207 commit 2f24fea
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
9 changes: 6 additions & 3 deletions starlette/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,9 +489,12 @@ def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] in ("http", "websocket"):
headers = Headers(scope=scope)
host = headers.get("host", "").split(":")[0]
match = self.host_regex.match(host)
if match:
matched_params = match.groupdict()
host_match = self.host_regex.match(host)
path_match = self.routes == [] or any(
[route.matches(scope)[0] == Match.FULL for route in self.routes]
)
if host_match and path_match:
matched_params = host_match.groupdict()
for key, value in matched_params.items():
matched_params[key] = self.param_convertors[key].convert(value)
path_params = dict(scope.get("path_params", {}))
Expand Down
33 changes: 33 additions & 0 deletions tests/test_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1159,3 +1159,36 @@ async def startup() -> None:
... # pragma: nocover

router.on_event("startup")(startup)


def host_endpoint(request):
name = request.path_params["name"]
return JSONResponse({"name": name})


host_based_router = Router(
routes=[
Host(
"example.org",
app=Router([Route("/foo/{name}", host_endpoint, name="foo")]),
),
Host(
"example.org",
app=Router([Route("/bar/{name}", host_endpoint, name="bar")]),
),
],
)


def test_host_based_routing(test_client_factory):
client = test_client_factory(host_based_router, base_url="https://example.org/")

response = client.get("/foo/foo")
assert response.status_code == 200
assert response.json() == {"name": "foo"}

client = test_client_factory(host_based_router, base_url="https://example.org/")

response = client.get("/bar/bar")
assert response.status_code == 200
assert response.json() == {"name": "bar"}

0 comments on commit 2f24fea

Please sign in to comment.