public Yoke listen(final @NotNull HttpServer server) {
server.requestHandler(new Handler<HttpServerRequest>() {
@Override
public void handle(HttpServerRequest req) {
// the context map is shared with all middlewares
final YokeRequest request = requestWrapper.wrap(req, new Context(defaultContext), engineMap, store);
// add x-powered-by header is enabled
Boolean poweredBy = request.get("x-powered-by");
if (poweredBy != null && poweredBy) {
request.response().putHeader("x-powered-by", "yoke");
}
new Handler<Object>() {
int currentMiddleware = -1;
@Override
public void handle(Object error) {
if (error == null) {
currentMiddleware++;
if (currentMiddleware < middlewareList.size()) {
final MountedMiddleware mountedMiddleware = middlewareList.get(currentMiddleware);
if (!mountedMiddleware.enabled) {
// the middleware is disabled
handle(null);
} else {
if (request.path().startsWith(mountedMiddleware.mount)) {
mountedMiddleware.middleware.handle(request, this);
} else {
// the middleware was not mounted on this uri, skip to the next entry
handle(null);
}
}
} else {
HttpServerResponse response = request.response();
// reached the end and no handler was able to answer the request
response.setStatusCode(404);
response.setStatusMessage(HttpResponseStatus.valueOf(404).reasonPhrase());
if (errorHandler != null) {
errorHandler.handle(request, null);
} else {
response.end(HttpResponseStatus.valueOf(404).reasonPhrase());
}
}
} else {
request.put("error", error);
if (errorHandler != null) {
errorHandler.handle(request, null);
} else {
HttpServerResponse response = request.response();
int errorCode;
// if the error was set on the response use it
if (response.getStatusCode() >= 400) {
errorCode = response.getStatusCode();