vertx 如何使用查询参数重新路由
vertx how to reroute with query params
由于某些 url 版本控制,我们尝试将多个路径映射到同一个处理程序。
我尝试通过重新路由实现此目的,但查询参数在此过程中丢失。
// reroute if the path contains apiv3 / api v3
router.route("/apiv3/*").handler( context -> {
String path = context.request().path();
path = path.replace("apiv3/", "");
LOG.info("Path changed to {}", path);
context.reroute(path);
});
解决这个问题最优雅的方法是什么?
有一些关于 google 组的讨论,但令人惊讶的是,没有什么可以快速简单地实施。
reroute 文档说:
It should be clear that reroute works on paths, so if you need to
preserve and or add state across reroutes, one should use the
RoutingContext object.
因此您可以创建一个全局 catch-all 路由,将任何查询参数存储在 RoutingContext
:
router.route().handler(ctx -> {
ctx.put("queryParams", ctx.queryParams());
ctx.next();
});
那么你的apiv3
catch-all路线:
router.route("/apiv3/*").handler( context -> {
String path = context.request().path();
path = path.replace("apiv3/", "");
LOG.info("Path changed to {}", path);
context.reroute(path);
});
最后一个实际的路由处理程序:
router.get("/products").handler(rc -> {
MultiMap queryParams = rc.get("queryParams");
// handle request
});
由于某些 url 版本控制,我们尝试将多个路径映射到同一个处理程序。
我尝试通过重新路由实现此目的,但查询参数在此过程中丢失。
// reroute if the path contains apiv3 / api v3
router.route("/apiv3/*").handler( context -> {
String path = context.request().path();
path = path.replace("apiv3/", "");
LOG.info("Path changed to {}", path);
context.reroute(path);
});
解决这个问题最优雅的方法是什么?
有一些关于 google 组的讨论,但令人惊讶的是,没有什么可以快速简单地实施。
reroute 文档说:
It should be clear that reroute works on paths, so if you need to preserve and or add state across reroutes, one should use the RoutingContext object.
因此您可以创建一个全局 catch-all 路由,将任何查询参数存储在 RoutingContext
:
router.route().handler(ctx -> {
ctx.put("queryParams", ctx.queryParams());
ctx.next();
});
那么你的apiv3
catch-all路线:
router.route("/apiv3/*").handler( context -> {
String path = context.request().path();
path = path.replace("apiv3/", "");
LOG.info("Path changed to {}", path);
context.reroute(path);
});
最后一个实际的路由处理程序:
router.get("/products").handler(rc -> {
MultiMap queryParams = rc.get("queryParams");
// handle request
});