Skip to content

Instantly share code, notes, and snippets.

@aesteve
Created October 11, 2016 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aesteve/4cf52a42f0439ab1f9ebebaf17121c5c to your computer and use it in GitHub Desktop.
Save aesteve/4cf52a42f0439ab1f9ebebaf17121c5c to your computer and use it in GitHub Desktop.
Creating interceptor-like logic just with handlers
public class InterceptorExample extends AbstractVerticle {
public final static String API_PATH = "/api/v1/";
public final static String STATIC_FILES = "/static/";
// ...
private Router router;
@Override
public void start(Future<Void> future) {
router = Router.router(vertx);
attachRoutes();
vertx
.createHttpServer()
.requestHandler(router::accept)
.listen(future.map<Void>(s -> null).completer());
}
private void attachRoutes() {
router.get(STATIC_FILES + "*").handler(SomeUtilityClass::createCacheHeaders);
router.get(STATIC_FILES + "*").handler(StaticHandler.create());
jsonRoute(API_PATH + "orders", ctx -> {
final Collection<Order> orders = yourBusinessService.getOrders();
ctx.put("data", orders);
ctx.next();
});
}
private void jsonRoute(String path, Handler<RoutingContext> businessLogic) {
router.route(path).handler(JsonUtils::prepareHeaders);
router.route(path).handler(businessLogic);
router.route(path).handler(JsonUtils::marshallResult);
}
}
interface JsonUtils { // this is what you're calling an interceptor
static void prepareHeaders(RoutingContext ctx) {
if (!ctx.request.headers().contains("something")) {
ctx.fail(400);
return;
}
ctx.response().putHeader(CONTENT_TYPE, "application/json");
ctx.next();
}
static void marshallResult(RoutingContext ctx) {
ctx.response().end(ctx.get("data").toJsonObject()); // or Jackson if you want to stay generic, or whatever you need
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment