Skip to content

Commit

Permalink
Implement JSON response in PingService and add client IP and host hea…
Browse files Browse the repository at this point in the history
…der retrieval
  • Loading branch information
mkjsix committed Nov 18, 2024
1 parent 3114cef commit 81f482d
Showing 1 changed file with 31 additions and 14 deletions.
45 changes: 31 additions & 14 deletions core/src/main/java/org/restheart/services/PingService.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
import org.restheart.plugins.RegisterPlugin;
import org.restheart.utils.HttpStatus;

import io.undertow.server.HttpServerExchange;

/**
*
* @author Andrea Di Cesare {@literal <[email protected]>}
Expand All @@ -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 = "<div><h2>" + msg + "</h2></div>";
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();
}
}
}

0 comments on commit 81f482d

Please sign in to comment.