Skip to content

Instantly share code, notes, and snippets.

@teivah
Created May 30, 2018 13:25
Show Gist options
  • Save teivah/b375124a066e5c4784a7c5da4ac4c781 to your computer and use it in GitHub Desktop.
Save teivah/b375124a066e5c4784a7c5da4ac4c781 to your computer and use it in GitHub Desktop.
public void start(Future<Void> startFuture) {
final Router router = Router.router(vertx);
// Create a BodyHandler to have the capability to retrieve the body
router.route().handler(BodyHandler.create());
router.route(HttpMethod.POST, "/file").handler(routingContext -> {
HttpServerResponse response = routingContext.response();
// Retrieve the body as a JsonObject
JsonObject body = routingContext.getBodyAsJson();
// Get the filename attribute value
String filename = body.getString("filename");
// Execute a blocking part
vertx.executeBlocking(future -> {
byte[] bytes = parseLargeFile(filename);
// Complete the future with the generated objects in the
// blocking method
future.complete(bytes);
} , res -> {
if (res.succeeded()) {
// If the blocking part succeedeed
byte[] bytes = (byte[]) res.result();
response.putHeader("Content-Type", "application/octet-stream");
response.setChunked(true);
response.write(Buffer.buffer(bytes));
response.setStatusCode(200);
response.end();
} else {
// Otherwise we manage to return an error
response.setStatusCode(500);
response.setStatusMessage("Internal error: " + res.cause().getMessage());
response.end();
}
});
});
vertx.createHttpServer().requestHandler(router::accept).listen(8080, result -> {
if (result.succeeded()) {
startFuture.complete();
} else {
startFuture.fail(result.cause());
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment