Add a router helper to get the mounted base path of the current Hono instance
enhancement
### What is the feature you are proposing?
sample code
```ts
const app = new Hono();
const sub1 = new Hono();
const sub2 = new Hono();
const sub3 = new Hono();
sub3.get("/assets/*", async (c, next) => {
const logStr = JSON.stringify({
path: c.req.path,
url: c.req.url,
routeIndex: c.req.routeIndex,
param: c.req.param(),
routeLib: {
routePath: routePath(c),
basePath: basePath(c),
baseRoutePath: baseRoutePath(c),
matchedRoutes: matchedRoutes(c).map((r) => ({
method: r.method,
path: r.path,
basePath: r.basePath,
handler: r.handler.name,
})),
}
}, null, 2);
console.log(logStr);
return c.text("ok");
});
sub2.route("/:app/sub3/assets", sub3);
sub1.route("/:app/sub2/assets", sub2);
app.route("/:app/sub1/assets", sub1);
app.notFound((c) => {
return c.text('Custom 404 Message', 404)
});
app.onError((err, c) => {
console.error(`${err}`)
return c.text('Custom Error Message', 500)
});
serve({
fetch: app.fetch,
port: 52060,
}, (info) => {
console.log(`Server is listening on ${info.address}:${info.port}`);
});
```
When I access:
> http://localhost:52060/s1/sub1/assets/ss2/sub2/assets/sss3/sub3/assets/assets/file-hoge/assets/assets-kage.js
I get the following log:
```json
{
"path": "/s1/sub1/assets/ss2/sub2/assets/sss3/sub3/assets/assets/file-hoge/assets/assets-kage.js",
"url": "http://localhost:52060/s1/sub1/assets/ss2/sub2/assets/sss3/sub3/assets/assets/file-hoge/assets/assets-kage.js",
"routeIndex": 0,
"param": {
"app": "s1"
},
"routeLib": {
"routePath": "/:app/sub1/assets/:app/sub2/assets/:app/sub3/assets/assets/*",
"basePath": "/s1/sub1/assets",
"baseRoutePath": "/:app/sub1/assets",
"matchedRoutes": [
{
"method": "GET",
"path": "/:app/sub1/assets/:app/sub2/assets/:app/sub3/assets/assets/*",
"basePath": "/:app/sub1/assets",
"handler": ""
}
]
}
}
```
Inside `sub3.get`, I want to get the path relative to `sub3`:
`/assets/assets/file-hoge/assets/assets-kage.js`
To do that, I need to remove the following prefix from the beginning of `c.req.path`:
`/s1/sub1/assets/ss2/sub2/assets/sss3/sub3`
However, none of the values I can get from routeLib seem to provide this expanded prefix string.
The paths returned by `routePath`, `baseRoutePath`, and `matchedRoutes` still contain unexpanded params.
The only value where params are expanded is `basePath`, but it only contains:
`/s1/sub1/assets`
It would be very useful if this contained the full mounted base path, like:
`/s1/sub1/assets/ss2/sub2/assets/sss3/sub3`
The path structure in this example is intentionally tricky for explanation purposes.
The Hono instances are nested through multiple `route()` calls.
I intentionally included "/assets/" in many places to avoid relying on string search.
All path params use the same name, `:app`. Because of that, `c.req.param()` only returns the first matched value, s1.
So currently, I cannot reliably get the path relative to the nested sub3 app without doing fragile string manipulation.
0 条评论