diff --git a/core/src/main/java/org/restheart/services/PingService.java b/core/src/main/java/org/restheart/services/PingService.java index 760c0eabb..c2e4dc30e 100644 --- a/core/src/main/java/org/restheart/services/PingService.java +++ b/core/src/main/java/org/restheart/services/PingService.java @@ -30,6 +30,8 @@ import org.restheart.plugins.RegisterPlugin; import org.restheart.utils.HttpStatus; +import io.undertow.server.HttpServerExchange; + /** * * @author Andrea Di Cesare {@literal } @@ -46,26 +48,41 @@ public void setup() { this.msg = argOrDefault(this.config, "msg", "Greetings from RESTHeart!"); } - /** - * - */ @Override - public void handle(ByteArrayRequest request, ByteArrayResponse response) throws Exception { + public void handle(final ByteArrayRequest request, final ByteArrayResponse response) throws Exception { if (request.isGet()) { - var accept = request.getHeader("Accept"); - - if (accept != null && accept.startsWith("text/html")) { - var content = "

" + msg + "

"; - response.setContent(content.getBytes()); - response.setContentType("text/html"); - } else { - response.setContentType("text/plain"); - response.setContent(msg.getBytes()); - } + final StringBuilder pingMessageBuilder = new StringBuilder(); + pingMessageBuilder.append("{\"message\": \"") + .append(msg) + .append("\", \"client_ip\": \"") + .append(getClientIp(request.getExchange())) + .append("\", \"host\": \"") + .append(getHostHeader(request.getExchange())) + .append("\"}"); + final String pingMessage = pingMessageBuilder.toString(); + response.setContentType("application/json"); + response.setContent(pingMessage.getBytes()); } else if (request.isOptions()) { handleOptions(request); } else { response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); } } + + private String getHostHeader(final HttpServerExchange exchange) { + return exchange.getRequestHeaders().getFirst("Host"); + } + + private String getClientIp(final HttpServerExchange exchange) { + // Get the X-Forwarded-For header from the request + final String forwardedFor = exchange.getRequestHeaders().getFirst("X-Forwarded-For"); + + if (forwardedFor != null && !forwardedFor.isEmpty()) { + // The first IP in X-Forwarded-For is typically the client's IP + return forwardedFor.split(",")[0].trim(); + } else { + // Fallback to the remote address from the exchange + return exchange.getSourceAddress().getAddress().getHostAddress(); + } + } }