26

How to rewrite HTTP-Request-Paths in Quarkus - ITNEXT

 4 years ago
source link: https://itnext.io/how-to-rewrite-http-request-paths-in-quarkus-aa85c3400d95?source=friends_link&gi=9f6596a54162
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to rewrite HTTP-Request-Paths in Quarkus

In our project we have the a REST-Api listening on BASE_PATH/v1.0/resource. Now people also want to access this via calling BASE_PATH/v1/resource. This article shows you how you can achieve this in Quarkus without additional external tooling.

Image for post
Image for post

Bild von Gerald Schmidtkunz auf Pixabay

Quarkus internally builds on a number of technologies of which one is Eclipse Vert.x. Vert.x Web Router (and its included Netty) provide the lower layer of the HTTP-stack, on which then other layers like the OpenAPI servlet or RestEasy for JAX-RS build upon. This means, that every incoming HTTP-request passes Vert.X before it is dispatched.

Image for post
Image for post

Way of a HTTP-Request through the stack

If you look at the above, then it becomes clear that Vert.x is the place for such rewriting handling (it could be Netty, but while Netty is powerful, it is also too low level to deal with; Vert.x does a lot of the heavy lifting there and is the best layer to do it).

Vert.x offers so called RouteFilters, that can be inserted into the internal forwarding path. Those filters are just special kinds of Vert.x route handlers, where the method doing the work is annotated with io.quarkus.vertx.web.RouteFilter.

@RouteFilter(400)                             //  (1)
void myRedirector(RoutingContext rc) {
String uri = rc.request().uri(); // (2)

if (uri.startsWith("BASE_PATH/v1/")) { // (3)
String remain = uri.substring("BASE_PATH/v1/".length()); // (4)

rc.reroute("BASE_PATH/v1.0/" +remain); // (5)
return; // <-- This is important here
}
rc.next();
}

In (1) we need to give the filter a priority; a higher number means the filter is called earlier than filters with lower priority. In (2) we determine the request-URI. If it matches the prefix we want to rewrite (3), we determine the remaining part of the URI (4), which also contains the query parameters etc. In (5) we call reroute() with the new URI to signal Vert.x it should do the rewriting. It is important to remember to not call rc.next() afterwards, as this would confuse Vert.x.

Conclusion

The Vert.x web router is the logical point within Quarkus to modify HTTP requests independent of the used application framework in higher layers. You can also read more about the interaction of Quarkus and Vert.x at the Reactive Route guide.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK