Routing support for wildcard parameters
What is the feature you are proposing?
Currently Hono's routing provides support for a number of parameters. However, there is no first-class support for usecases such as:
- a request is routed by prefix,
- hono sets a parameter by stripping the prefix from the request path,
- the route handler passes the parameter (i.e., request's path with the prefix stripped) to a subrequest and/or origin server.
This type of usecase happens frequently when using Cloudflare Workers. Currently, the best way to address this usecase is to manually put together the parameter, similar to:
app.get('/someprefix/*', async (c, next) => {
const path = getPathFromURL(c.req.url)
const parameter = path.replace(/^\/someprefix\//, ''))
// do things
})
This works ok, but it leads to a subpar developer experience. I suppose that this could be done with regex parameters too.
Ideally, Hono would do this for us. It would be great if Hono provided support for wildcard parameters, where anything matching a wildcard would be conveniently provided through a parameter, similar to:
app.get('/someprefix/:parameter*', async (c, next) => {
// do things
})
This topic was briefly touched in #591 , but so far without a response.
Would it be possible to implement wildcard parameters?
I think you can implement wildcard parameter by regexp patameter
app.get('/posts/:path{.+}', async (c) => {
return c.text(c.req.param("path"))
})
One thing to add is that there is a way to implement this type of wildcard routing without compromising performance. @yusukebe What do you think?
app.get('/someprefix/:parameter*', async (c, next) => {
// do things
})
https://www.typescriptlang.org/play/?#code/MYewdgzgLgBKYDcCmAnKB1AlgGwCbAEMVcAFIggWwBUQAlJAcwFEAPABzJUpgF4YAKNkSgAuGNBSYwDAJS8AfDADeAKBjqYKJFACuKMDCFoAdFrbYCwJPwD0-EcYDUMgDoAqACQ2ANDABEHgCMSk4Avn4yKqEqKvAQINhIxtggDPzwyGhYeITEnJQ09Mzs+RT8fiKYuBGRcQlJKWkZqBg4+ESk5NR0jKwcXeUiQlAAFm41seDxicmp6eCZrTkdpYW9JQN+0ARQmMA1QA
Hi @ruimaciel
As @EdamAme-x said, it can support a wildcard parameter with regexp like the following:
app.get('/posts/:path{.+}', async (c) => {
return c.text(c.req.param("path"))
})
@EdamAme-x
Indeed, supporting /:parameter* will decrease the user's confusion. But, hmm. In my opinion, it's okay whether we do it or not.
Regarding this issue, this can be done with a regexp like /posts/:path{.+}. So it does not need to remain open. Closing.