BlackSheep icon indicating copy to clipboard operation
BlackSheep copied to clipboard

Why is it necessary to add a slash (/) at the end of the URL when accessing routes registered in a sub-application?

Open satori1995 opened this issue 1 year ago • 2 comments

I've encountered a puzzling issue while using blacksheep

Let's take a simple example

from blacksheep import Application, Request, text
import uvicorn

app = Application()
child_app = Application()

@child_app.router.get("/")
async def test_header(request: Request):
    if request.headers.get_first(b"Authorization") is None:
        return text("Authentication not in request headers")
    else:
        return text("Authentication in request headers")

app.mount_registry.auto_events = True
app.mount("/sub-child", child_app)

if __name__ == '__main__':
    uvicorn.run("main:app", port=8000)

Then we separately access /sub-child and /sub-child/

import requests

resp = requests.get("http://localhost:8000/sub-child",
                    headers={"Authorization": "..."})
print(resp.text)  # Authentication not in request headers
resp = requests.get("http://localhost:8000/sub-child/",
                    headers={"Authorization": "..."})
print(resp.text)  # Authentication in request headers

Judging from the results, /sub-child/ gives the correct output. However, I'm curious as to why accessing /sub-child yields an unexpected result. I assumed that both should essentially function the same way

PS: I recently came across the blacksheep framework on a website which listed Python's ASGI frameworks. It showed that its concurrency was much higher than FastAPI, so after a brief period of learning, I applied it to my project. However, now I'm encountering the issue I mentioned above. While it can be resolved by adding a slash (/) at the end of the URL, I'm still curious about the underlying reason.

In fact, a similar issue arises with cross-origin resource sharing (child_app.use_cors). Accessing /sub-child/ allows successful CORS, but accessing /sub-child results in a failure.

I sincerely ask for your help in answering this. Thank you very much

satori1995 avatar Jul 13 '23 17:07 satori1995