default <T extends Throwable> void error( RoutingContext context, HttpResponseStatus code, String message, T object) { HttpServerResponse response = context.response().setStatusCode(code.code()); response.putHeader("X-API-Gateway-Error", "true"); if (message == null) { response.setStatusMessage(code.reasonPhrase()); } else { response.setStatusMessage(message); } if (object != null) { JsonObject errorResponse = new JsonObject() .put("errorType", object.getClass().getSimpleName()) .put("message", object.getMessage()); response .setChunked(true) .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .end(errorResponse.toString(), "UTF-8"); } else { response.end(); } }
public static void main(String[] args) { Vertx vertx = null; HttpServer server = Vertx.vertx().createHttpServer(); Router router = Router.router(vertx); Route route = router.route().path("/some/path/"); route.handler( routingContext -> { // This handler will be called for the following request paths: // `/some/path` // `/some/path/` // `/some/path//` // // but not: // `/some/path/subdir` // This handler will be called for every request HttpServerResponse response = routingContext.response(); response.putHeader("content-type", "text/plain"); // Write to the response and end it response.end("Hello World from Vert.x-Web! Some path, Simple REST"); }); router .route() .handler( routingContext -> { // This handler will be called for every request HttpServerResponse response = routingContext.response(); response.putHeader("content-type", "text/plain"); // Write to the response and end it response.end("Hello World from Vert.x-Web!"); }); server.requestHandler(router::accept).listen(8080); }
/* * We got more than 8 lines on that method because * we could not really delegates more for other * function. That would made the code kind of hard * to read. * */ private void getDemandExerciseRoutine(RoutingContext context) { String id = context.request().getParam("id"); Path path = Paths.get(this.workingDirectory.toString(), id + ".mkdown"); HttpServerResponse rep = context.response().setChunked(true).putHeader("content-type", "text/html"); if (Files.exists(path)) { MarkdownToHTML markdownToHTML = new MarkdownToHTML(); try { rep.write(markdownToHTML.parse(path)); } catch (IOException e) { rep.write("Unable to load " + id + ".mkdow"); } } else { rep.write("Excercice with id " + id + " no found"); } rep.end(); }