import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Locale; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; /** A dependency-free backend for the gateway probes. Run with: java scripts/Echo.java 9091 */ public class Echo { public static void main(String[] args) throws IOException { AtomicInteger flaky = new AtomicInteger(); HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", Integer.parseInt(args[0])), 0); // Prints the forwarding headers exactly as they arrived, so we see what the gateway sent upstream. server.createContext("/headers", ex -> { var found = new TreeMap(); ex.getRequestHeaders().forEach((name, values) -> { String n = name.toLowerCase(Locale.ROOT); if (n.equals("forwarded") || n.startsWith("x-forwarded")) found.put(n, String.join(" | ", values)); }); StringBuilder body = new StringBuilder(); found.forEach((k, v) -> body.append(k).append(": ").append(v.replaceAll("127\\.0\\.0\\.1:\\d+", "127.0.0.1:")).append('\n')); if (found.isEmpty()) body.append("(no Forwarded or X-Forwarded-* header at all)\n"); reply(ex, 200, body.toString()); }); // Always 500, and counts how often it was called. server.createContext("/flaky", ex -> { flaky.incrementAndGet(); reply(ex, 500, "boom\n"); }); server.createContext("/count", ex -> reply(ex, 200, "upstream calls to /flaky: " + flaky.getAndSet(0) + "\n")); server.start(); System.out.println("echo on " + args[0]); } private static void reply(com.sun.net.httpserver.HttpExchange ex, int status, String body) throws IOException { byte[] bytes = body.getBytes(); ex.getResponseHeaders().add("Content-Type", "text/plain"); ex.sendResponseHeaders(status, bytes.length); ex.getResponseBody().write(bytes); ex.close(); } }