### Create a Proxy with Options using HttpProxy.reverseProxy(ProxyOptions, HttpClient) Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt This example shows how to create an `HttpProxy` with custom options, such as enabling caching and ensuring WebSocket support. Use this factory method when you require configurations beyond the defaults. ```java import io.vertx.httpproxy.HttpProxy; import io.vertx.httpproxy.ProxyOptions; import io.vertx.httpproxy.cache.CacheOptions; ProxyOptions options = new ProxyOptions() .setCacheOptions(new CacheOptions().setMaxSize(500)) // enable cache, 500 entries .setSupportWebSocket(true); // WebSocket proxying on (default) HttpProxy proxy = HttpProxy.reverseProxy(options, proxyClient); proxy.origin(7070, "origin"); proxyServer.requestHandler(proxy).listen(8080); ``` -------------------------------- ### Load Test Certificates in Java with PemKeyCertOptions Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/test/resources/SSL_TEST_CERTIFICATES.txt Demonstrates how to load test SSL certificates from the classpath in Java using PemKeyCertOptions. This is typically used in test setups for HTTPS configurations. ```java PemKeyCertOptions pemOptions = new PemKeyCertOptions() .setCertPath("server.cert.pem") .setKeyPath("server.key.pem"); ``` -------------------------------- ### Dynamic Origin Routing with HttpProxy.origin(OriginRequestProvider) Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt This example demonstrates dynamic origin routing using an `OriginRequestProvider`. This allows for per-request target server resolution, enabling features like load balancing or A/B testing. The provider selects the origin based on a custom header. ```java import io.vertx.core.net.SocketAddress; import io.vertx.httpproxy.OriginRequestProvider; // Route based on a custom header proxy.origin(OriginRequestProvider.selector(proxyContext -> { String tenant = proxyContext.request().headers().get("X-Tenant"); int port = "acme".equals(tenant) ? 9001 : 9002; return Future.succeededFuture(SocketAddress.inetSocketAddress(port, "backend.internal")); })); ``` -------------------------------- ### Set a Fixed Origin with HttpProxy.origin(int port, String host) Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt This method configures the proxy to forward all incoming traffic to a single, fixed origin server specified by its port and host. This is the most straightforward routing setup. ```java HttpProxy proxy = HttpProxy.reverseProxy(proxyClient); // Every request will be forwarded to backend.internal:9090 proxy.origin(9090, "backend.internal"); ``` -------------------------------- ### Create a Basic Reverse Proxy with HttpProxy.reverseProxy(HttpClient) Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt This snippet demonstrates how to create a basic reverse proxy using `HttpProxy.reverseProxy(HttpClient)`. It configures the proxy to forward requests to a specified origin server and mounts it as the request handler for an HTTP server. Ensure you have a Vert.x instance and an HttpClient configured. ```java import io.vertx.core.Vertx; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpServer; import io.vertx.httpproxy.HttpProxy; Vertx vertx = Vertx.vertx(); // Create the HttpClient used to forward requests to the origin HttpClient proxyClient = vertx.createHttpClient(); // Build the reverse proxy and point it at the origin (port 7070, host "origin") HttpProxy proxy = HttpProxy.reverseProxy(proxyClient); proxy.origin(7070, "origin"); // Mount the proxy as the request handler of the proxy server HttpServer proxyServer = vertx.createHttpServer(); proxyServer.requestHandler(proxy).listen(8080); // All requests arriving at :8080 are transparently forwarded to origin:7070 ``` -------------------------------- ### Create a proxy with options Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Creates an HttpProxy instance with fine-grained options controlling caching, WebSocket support, and forwarded-header behaviour. ```APIDOC ## HttpProxy.reverseProxy(ProxyOptions, HttpClient) — Create a proxy with options ### Description Creates an `HttpProxy` instance with fine-grained options controlling caching, WebSocket support, and forwarded-header behaviour. Use this factory when you need more than the default configuration. ### Method ```java HttpProxy proxy = HttpProxy.reverseProxy(options, proxyClient); ``` ### Parameters * `options` (ProxyOptions) - Options to configure the proxy. * `proxyClient` (HttpClient) - The HttpClient used to forward requests to the origin. ``` -------------------------------- ### Create a Reverse Proxy Server Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Set up a proxy server that listens on port 8080 and forwards requests to an origin server. ```java { // Use examples.HttpProxyExamples#proxy } ``` -------------------------------- ### Create a basic reverse proxy Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Creates an HttpProxy instance backed by the provided HttpClient. This is the primary entry point for all proxy configurations. ```APIDOC ## HttpProxy.reverseProxy(HttpClient) — Create a basic reverse proxy ### Description Creates an `HttpProxy` instance backed by the provided `HttpClient`. The returned proxy implements `Handler` and can be passed directly to `HttpServer.requestHandler()`. This is the primary entry point for all proxy configurations. ### Method ```java HttpProxy proxy = HttpProxy.reverseProxy(proxyClient); ``` ### Parameters * `proxyClient` (HttpClient) - The HttpClient used to forward requests to the origin. ``` -------------------------------- ### Enable and Configure Forwarded Headers Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Enable the addition of 'X-Forwarded-*' headers to requests sent to the origin server. ```java { // Use examples.HttpProxyExamples#forwardedHeaders } ``` -------------------------------- ### Create HTTP Body Abstraction Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Wrap HTTP bodies using `Body` objects, which can be created from a `Buffer` or a streaming `ReadStream`. Specify media type and length if known. ```java import io.vertx.httpproxy.Body; import io.vertx.httpproxy.MediaType; import io.vertx.core.buffer.Buffer; // From a buffer with media type Body jsonBody = Body.body( Buffer.buffer("{\"hello\":\"world\"}"), MediaType.APPLICATION_JSON ); // From a stream with known length ReadStream stream = /* some stream */; Body streamBody = Body.body(stream, 1024L, "text/csv"); // From a stream with unknown length (-1) Body unknownLengthBody = Body.body(stream); // Use in an interceptor to replace the response body proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyResponse(ProxyContext context) { context.response().setBody(jsonBody); return context.sendResponse(); } }); ``` -------------------------------- ### Route Traffic with an Origin Selector Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Configure a proxy to route traffic to a specific origin server using a selector function. ```java { // Use examples.HttpProxyExamples#originSelector } ``` -------------------------------- ### Configure Proxy Options with Cache, WebSocket, and Forwarded Headers Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Groups proxy-level settings including cache configuration, WebSocket support, and forwarded header behavior. Serializes to/from JSON. ```java import io.vertx.httpproxy.ProxyOptions; import io.vertx.httpproxy.ForwardedHeadersOptions; import io.vertx.httpproxy.cache.CacheOptions; ProxyOptions options = new ProxyOptions() .setCacheOptions( new CacheOptions() .setMaxSize(2000) .setShared(true) .setName("my-proxy-cache") ) .setSupportWebSocket(true) .setForwardedHeadersOptions( new ForwardedHeadersOptions() .setEnabled(true) .setForwardFor(true) .setForwardProto(true) .setForwardHost(true) .setForwardPort(false) ); HttpProxy proxy = HttpProxy.reverseProxy(options, proxyClient); proxy.origin(7070, "origin"); ``` -------------------------------- ### Create Custom Origin Request with OriginRequestProvider Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Use `OriginRequestProvider` to build `HttpClientRequest` from scratch, allowing custom `RequestOptions` like SSL, headers, and timeouts based on the `ProxyContext`. This provides maximum flexibility in defining the request to the origin server. ```java import io.vertx.core.http.RequestOptions; import io.vertx.httpproxy.OriginRequestProvider; proxy.origin(proxyContext -> { // Determine target based on request URI prefix String uri = proxyContext.request().getURI(); String host = uri.startsWith("/api/v2") ? "v2.backend.internal" : "v1.backend.internal"; RequestOptions opts = new RequestOptions() .setHost(host) .setPort(443) .setSsl(true); return proxyContext.client().request(opts); }); ``` -------------------------------- ### Configure Proxy Caching Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Enable response caching for the proxy by setting the cache options. By default, caching is disabled. ```java { // Use examples.HttpProxyExamples#cacheConfig } ``` -------------------------------- ### Provide Custom Client Request for Origin Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Define a function to create the client request to the origin server for maximum flexibility. ```java { // Use examples.HttpProxyExamples#originRequestProvider } ``` -------------------------------- ### ProxyOptions Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt A configuration object that groups various proxy-level settings, including caching, WebSocket support, and forwarded header behavior. It can be serialized to and from JSON. ```APIDOC ## `ProxyOptions` — Proxy configuration object A data object that groups all proxy-level settings: caching, WebSocket support, and forwarded-header behaviour. Serialises to/from JSON. ```java import io.vertx.httpproxy.ProxyOptions; import io.vertx.httpproxy.ForwardedHeadersOptions; import io.vertx.httpproxy.cache.CacheOptions; ProxyOptions options = new ProxyOptions() .setCacheOptions( new CacheOptions() .setMaxSize(2000) .setShared(true) .setName("my-proxy-cache") ) .setSupportWebSocket(true) .setForwardedHeadersOptions( new ForwardedHeadersOptions() .setEnabled(true) .setForwardFor(true) .setForwardProto(true) .setForwardHost(true) .setForwardPort(false) ); HttpProxy proxy = HttpProxy.reverseProxy(options, proxyClient); proxy.origin(7070, "origin"); ``` ``` -------------------------------- ### Selectively Enable Forwarded Headers Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Configure which specific 'X-Forwarded-*' headers should be added to proxied requests. ```java { // Use examples.HttpProxyExamples#forwardedHeadersSelective } ``` -------------------------------- ### Add Gradle Dependency for Vert.x Http Proxy Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Add this line to your build.gradle file to include Vert.x Http Proxy. ```groovy dependencies { compile 'io.vertx:vertx-http-proxy:${maven.version}' } ``` -------------------------------- ### OriginRequestProvider - Full custom request creation Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Provides maximum flexibility to build the HttpClientRequest to the origin from scratch, including custom RequestOptions (SSL, headers, timeouts, etc.). ```APIDOC ## `OriginRequestProvider` — Full custom request creation Provides maximum flexibility: given the `ProxyContext`, build the `HttpClientRequest` to the origin from scratch, including custom `RequestOptions` (SSL, headers, timeouts, etc.). ```java import io.vertx.core.http.RequestOptions; import io.vertx.httpproxy.OriginRequestProvider; proxy.origin(proxyContext -> { // Determine target based on request URI prefix String uri = proxyContext.request().getURI(); String host = uri.startsWith("/api/v2") ? "v2.backend.internal" : "v1.backend.internal"; RequestOptions opts = new RequestOptions() .setHost(host) .setPort(443) .setSsl(true); return proxyContext.client().request(opts); }); ``` ``` -------------------------------- ### Configure HTTP Response Cache Options Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Set up an in-memory LRU cache for HTTP responses. Supports private caches or shared caches across multiple proxy instances using a specified name. ```java import io.vertx.httpproxy.cache.CacheOptions; // Private cache — not shared with other HttpProxy instances CacheOptions privateCache = new CacheOptions() .setMaxSize(1000); // default is 1000 entries // Shared cache — all proxies with the same name share the same store CacheOptions sharedCache = new CacheOptions() .setMaxSize(5000) .setShared(true) .setName("global-cache"); HttpProxy proxy = HttpProxy.reverseProxy( new ProxyOptions().setCacheOptions(sharedCache), proxyClient ); proxy.origin(7070, "origin"); ``` -------------------------------- ### Regenerate Test SSL Certificates with OpenSSL Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/test/resources/SSL_TEST_CERTIFICATES.txt Use this OpenSSL command to generate self-signed X.509 certificates and RSA private keys for testing purposes. The generated certificates are valid for 10 years and do not have a passphrase. ```bash openssl req -x509 \ -newkey rsa:2048 \ -keyout server.key.pem \ -out server.cert.pem \ -days 3650 \ -nodes \ -subj "/CN=localhost" ``` -------------------------------- ### Compose ProxyInterceptor with Fluent Builder Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Use `ProxyInterceptor.builder()` to declaratively compose common interceptor operations like path rewriting, header manipulation, and query parameter changes without writing boilerplate handler code. Multiple operations can be chained. ```java import io.vertx.httpproxy.ProxyInterceptor; import java.util.Set; // Chain multiple operations in a single interceptor ProxyInterceptor interceptor = ProxyInterceptor.builder() // Path manipulation .removingPathPrefix("/gateway") // strip /gateway prefix before forwarding .addingPathPrefix("/internal") // prepend /internal to the forwarded path // Request headers .transformingRequestHeaders(headers -> headers.set("X-Forwarded-By", "vertx-proxy")) .filteringRequestHeaders(Set.of("Cookie", "Authorization")) // remove sensitive headers // Response headers .filteringResponseHeaders(Set.of("X-Internal-Id", "X-Debug")) // Query params .settingQueryParam("version", "5") .removingQueryParam("internal_key") .build(); proxy.addInterceptor(interceptor); ``` -------------------------------- ### Send Immediate Response to User-Agent Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Send a response directly to the user-agent without requesting the origin server, altering the interception control flow. ```java proxy.addInterceptor(immediateResponse).listen(); ``` -------------------------------- ### Transform Plain-Text Response Body Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Replaces occurrences of 'internal-hostname' with 'api.example.com' in text/plain response bodies using UTF-8 encoding. Case-insensitive replacement. ```java import io.vertx.httpproxy.BodyTransformers; proxy.addInterceptor( ProxyInterceptor.builder() .transformingResponseBody( BodyTransformers.text( text -> text.replaceAll("(?i)\\binternal-hostname\\b", "api.example.com"), "UTF-8" ) ) .build() ); ``` -------------------------------- ### BodyTransformers.transform(MediaType, MediaType, Function) Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Provides the lowest-level body transformation by accepting raw buffer manipulation functions. Use this for custom binary data processing when built-in helpers are insufficient. ```APIDOC ## `BodyTransformers.transform(MediaType, MediaType, Function)` — Raw buffer transform The lowest-level body transformer: given consumed and produced `MediaType`s, applies a raw `Buffer -> Buffer` function. Use this when the built-in JSON/text helpers are insufficient. ```java import io.vertx.httpproxy.BodyTransformers; import io.vertx.httpproxy.MediaType; BodyTransformer gzipToRaw = BodyTransformers.transform( MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_OCTET_STREAM, buffer -> { // Custom binary manipulation return buffer; // replace with actual transform } ); proxy.addInterceptor( ProxyInterceptor.builder() .transformingResponseBody(gzipToRaw) .build() ); ``` ``` -------------------------------- ### ProxyInterceptor.builder() — Fluent interceptor builder Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Returns a ProxyInterceptorBuilder for declaratively composing common interceptor operations (path rewriting, header manipulation, query parameter manipulation, body transformation) without writing boilerplate handler code. ```APIDOC ## `ProxyInterceptor.builder()` — Fluent interceptor builder Returns a `ProxyInterceptorBuilder` for declaratively composing common interceptor operations (path rewriting, header manipulation, query parameter manipulation, body transformation) without writing boilerplate handler code. ```java import io.vertx.httpproxy.ProxyInterceptor; import java.util.Set; // Chain multiple operations in a single interceptor ProxyInterceptor interceptor = ProxyInterceptor.builder() // Path manipulation .removingPathPrefix("/gateway") // strip /gateway prefix before forwarding .addingPathPrefix("/internal") // prepend /internal to the forwarded path // Request headers .transformingRequestHeaders(headers -> headers.set("X-Forwarded-By", "vertx-proxy")) .filteringRequestHeaders(Set.of("Cookie", "Authorization")) // remove sensitive headers // Response headers .filteringResponseHeaders(Set.of("X-Internal-Id", "X-Debug")) // Query params .settingQueryParam("version", "5") .removingQueryParam("internal_key") .build(); proxy.addInterceptor(interceptor); ``` ``` -------------------------------- ### Use RFC 7239 Forwarded Header Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Configure the proxy to use the standardized 'Forwarded' header instead of 'X-Forwarded-*' headers. ```java { // Use examples.HttpProxyExamples#forwardedHeadersRfc7239 } ``` -------------------------------- ### ProxyContext.sendRequest / ProxyContext.sendResponse Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt `sendRequest()` continues the interceptor chain and then forwards the request to the origin, returning a `Future`. `sendResponse()` continues the chain and sends the response to the user-agent. ```APIDOC ## ProxyContext.sendRequest() / ProxyContext.sendResponse() ### Description `sendRequest()` continues the interceptor chain and then forwards the request to the origin, returning a `Future`. `sendResponse()` continues the chain and sends the response to the user-agent. ### Method ```java proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyRequest(ProxyContext context) { ProxyRequest req = context.request(); // Short-circuit: respond immediately without contacting the origin if ("/health".equals(req.getURI())) { req.release(); // release underlying resources ProxyResponse syntheticResp = req.response() .setStatusCode(200) .putHeader("content-type", "application/json") .setBody(Body.body(Buffer.buffer("{\"status\":\"UP\"}"), MediaType.APPLICATION_JSON)); return Future.succeededFuture(syntheticResp); } return context.sendRequest(); // proceed normally } }); ``` ``` -------------------------------- ### Maven Dependency for Vert.x HTTP Proxy Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Add this dependency to your project's pom.xml to include the Vert.x HTTP Proxy library. ```xml io.vertx vertx-http-proxy 5.1.0-SNAPSHOT ``` -------------------------------- ### ProxyRequest Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Allows inspection and mutation of outgoing requests forwarded to the origin server, including method, URI, headers, and body. ```APIDOC ## `ProxyRequest` — Mutable outgoing request Exposes and allows mutation of every facet of the request forwarded to the origin: HTTP method, URI, authority, headers, and body. Obtained from `ProxyContext.request()` inside an interceptor. ```java proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyRequest(ProxyContext context) { ProxyRequest req = context.request(); // Inspect System.out.println("Method : " + req.getMethod()); System.out.println("URI : " + req.getURI()); System.out.println("Version: " + req.version()); // Mutate req.setMethod(HttpMethod.GET); // force GET req.setURI("/v2" + req.getURI()); // rewrite URI req.putHeader("X-Request-Id", UUID.randomUUID().toString()); req.headers().remove("Cookie"); return context.sendRequest(); } }); ``` ``` -------------------------------- ### Add Maven Dependency for Vert.x Http Proxy Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Include this dependency in your pom.xml to use Vert.x Http Proxy. ```xml io.vertx vertx-http-proxy ${maven.version} ``` -------------------------------- ### Body Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Abstraction for HTTP bodies, supporting in-memory Buffers or streaming ReadStreams. Allows specifying media type and content length. ```APIDOC ## `Body` — HTTP body abstraction Wraps either a `Buffer` (in-memory) or a streaming `ReadStream` with an optional known length and `MediaType`. Created via static factory methods. ```java import io.vertx.httpproxy.Body; import io.vertx.httpproxy.MediaType; import io.vertx.core.buffer.Buffer; // From a buffer with media type Body jsonBody = Body.body( Buffer.buffer("{\"hello\":\"world\"}"), MediaType.APPLICATION_JSON ); // From a stream with known length ReadStream stream = /* some stream */; Body streamBody = Body.body(stream, 1024L, "text/csv"); // From a stream with unknown length (-1) Body unknownLengthBody = Body.body(stream); // Use in an interceptor to replace the response body proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyResponse(ProxyContext context) { context.response().setBody(jsonBody); return context.sendResponse(); } }); ``` ``` -------------------------------- ### CacheOptions Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Configure in-memory LRU caching for HTTP responses, respecting standard caching headers. Supports both private and shared caches. ```APIDOC ## `CacheOptions` — HTTP response cache configuration Enables an in-memory LRU cache that respects HTTP caching semantics (`Cache-Control`, `ETag`, `Expires`). Supports named shared caches across multiple proxy instances within the same Vert.x instance. ```java import io.vertx.httpproxy.cache.CacheOptions; // Private cache — not shared with other HttpProxy instances CacheOptions privateCache = new CacheOptions() .setMaxSize(1000); // default is 1000 entries // Shared cache — all proxies with the same name share the same store CacheOptions sharedCache = new CacheOptions() .setMaxSize(5000) .setShared(true) .setName("global-cache"); HttpProxy proxy = HttpProxy.reverseProxy( new ProxyOptions().setCacheOptions(sharedCache), proxyClient ); proxy.origin(7070, "origin"); ``` ``` -------------------------------- ### Set a fixed origin Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Configures the proxy to forward all traffic to a single origin server identified by host and port. ```APIDOC ## HttpProxy.origin(int port, String host) — Set a fixed origin ### Description Configures the proxy to forward all traffic to a single origin server identified by host and port. This is the simplest routing configuration. ### Method ```java proxy.origin(port, host); ``` ### Parameters * `port` (int) - The port of the origin server. * `host` (String) - The host of the origin server. ``` -------------------------------- ### Dynamic origin routing Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Replaces the fixed origin with a custom OriginRequestProvider that resolves the target server per-request, enabling dynamic dispatch logic. ```APIDOC ## HttpProxy.origin(OriginRequestProvider) — Dynamic origin routing ### Description Replaces the fixed origin with a custom `OriginRequestProvider` that resolves the target server per-request, enabling load balancing, A/B routing, or any dynamic dispatch logic. ### Method ```java proxy.origin(OriginRequestProvider); ``` ### Parameters * `OriginRequestProvider` - A provider that resolves the target server for each request. ``` -------------------------------- ### Create Body Interceptor from BodyTransformer Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Turn a BodyTransformer into a proxy interceptor using the builder pattern. ```java proxy.addInterceptor(bodyInterceptorTransformer).listen(); ``` -------------------------------- ### Intercept and Update Query Parameters Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Use a ProxyInterceptorBuilder to create an interceptor that updates or removes query parameters. Operations are applied in the order of configuration. ```java proxy.addInterceptor(queryInterceptorAdd).listen(); ``` -------------------------------- ### ProxyContext.set / ProxyContext.get Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Allows interceptors to attach arbitrary data to the request/response lifecycle, enabling communication between request-phase and response-phase interceptors. ```APIDOC ## ProxyContext.set(String, Object) / ProxyContext.get(String, Class) ### Description Allows interceptors to attach arbitrary data to the request/response lifecycle, enabling communication between request-phase and response-phase interceptors. ### Method ```java proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyRequest(ProxyContext context) { // Store request start time context.set("startTime", System.currentTimeMillis()); return context.sendRequest(); } @Override public Future handleProxyResponse(ProxyContext context) { long start = context.get("startTime", Long.class); long elapsed = System.currentTimeMillis() - start; context.response().headers().set("X-Response-Time", elapsed + "ms"); return context.sendResponse(); } }); ``` ``` -------------------------------- ### Transform Request/Response Body with BodyTransformer Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Use a BodyTransformer to create body transformations. A set of predefined transformations facilitates this process. ```java proxy.addInterceptor(bodyTransformer).listen(); ``` -------------------------------- ### Transform Request Path with Custom Function Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Apply an arbitrary function to the request URI before forwarding using `transformingPath`. Multiple calls to this method are applied in the order they are defined. ```java proxy.addInterceptor( ProxyInterceptor.builder() .transformingPath(uri -> uri.replace("/v1/", "/v2/")) // upgrade path version .build() ); ``` -------------------------------- ### Handle Proxy Request with Inbound Interceptor Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Implement inbound interceptors to perform operations on the proxy request before it's sent to the origin server. ```java proxy.addInterceptor(inboundInterceptor).listen(); ``` -------------------------------- ### BodyTransformers.jsonObject(Function) Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Creates a BodyTransformer that buffers the body, parses it as a JsonObject, applies the transformation function, and re-serialises it. Default maximum buffered size is 256 KB. ```APIDOC ## BodyTransformers.jsonObject(Function) ### Description Creates a `BodyTransformer` that buffers the body, parses it as a `JsonObject`, applies the transformation function, and re-serialises it. Default maximum buffered size is 256 KB. ### Method ```java proxy.addInterceptor( ProxyInterceptor.builder() .transformingResponseBody( BodyTransformers.jsonObject(json -> { // Remove PII before sending to the user-agent json.remove("ssn"); json.remove("creditCard"); json.put("_proxied", true); return json; }) ) .build() ); ``` ``` -------------------------------- ### Configure Max Buffered Size for JSON Body Transformation Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Provide a different maximum amount of bytes for buffering when performing JSON body transformations. The default is 256K bytes. ```java proxy.addInterceptor(bodyInterceptorJsonMaxBufferedSize).listen(); ``` -------------------------------- ### Configure Forwarded Headers Options Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Controls which proxy-identifying headers are appended to upstream requests. Disabled by default. ```java import io.vertx.httpproxy.ForwardedHeadersOptions; // Option A: selective X-Forwarded-* headers ForwardedHeadersOptions xForwardedOpts = new ForwardedHeadersOptions() .setEnabled(true) .setForwardFor(true) // adds X-Forwarded-For: .setForwardProto(true) // adds X-Forwarded-Proto: https .setForwardHost(true) // adds X-Forwarded-Host: .setForwardPort(false); // omit X-Forwarded-Port // Option B: RFC 7239 Forwarded header ForwardedHeadersOptions rfc7239Opts = new ForwardedHeadersOptions() .setEnabled(true) .setUseRfc7239(true); // adds: Forwarded: for=;proto=https;host= HttpProxy proxy = HttpProxy.reverseProxy( new ProxyOptions().setForwardedHeadersOptions(rfc7239Opts), proxyClient ); proxy.origin(7070, "origin"); ``` -------------------------------- ### Handle Proxy Response with Outbound Interceptor Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Implement outbound interceptors to perform operations on the proxy response after it's received from the origin server. ```java proxy.addInterceptor(outboundInterceptor).listen(); ``` -------------------------------- ### ProxyResponse Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Allows inspection and mutation of the response received from the origin before it is sent to the client, including status, headers, and body. ```APIDOC ## `ProxyResponse` — Mutable incoming response Exposes and allows mutation of the response received from the origin before it is delivered to the user-agent: status code, status message, headers, body, and cache metadata. ```java proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyResponse(ProxyContext context) { ProxyResponse resp = context.response(); // Inspect cache metadata System.out.println("Public cache : " + resp.publicCacheControl()); System.out.println("Max-Age : " + resp.maxAge()); System.out.println("ETag : " + resp.etag()); // Mutate if (resp.getStatusCode() == 404) { resp.setStatusCode(200) .setStatusMessage("OK") .putHeader("content-type", "application/json") .setBody(Body.body(Buffer.buffer("{\"found\":false}"), MediaType.APPLICATION_JSON)); } return context.sendResponse(); } }); ``` ``` -------------------------------- ### ProxyRequest.setAuthority Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Overrides the Host header (HTTP/1.1) or :authority pseudo-header (HTTP/2) sent to the origin. When overridden, the proxy automatically sets X-Forwarded-Host to the original authority. ```APIDOC ## ProxyRequest.setAuthority(HostAndPort) ### Description Overrides the `Host` header (HTTP/1.1) or `:authority` pseudo-header (HTTP/2) sent to the origin. When overridden, the proxy automatically sets `X-Forwarded-Host` to the original authority. ### Method ```java proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyRequest(ProxyContext context) { // Tell the origin server to treat the request as if it came from example.com:80 context.request().setAuthority(HostAndPort.create("example.com", 80)); return ProxyInterceptor.super.handleProxyRequest(context); } }); ``` ``` -------------------------------- ### Manipulate Query Parameters in Bulk Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Use `transformingQueryParams` to gain direct access to the full `MultiMap` of query parameters for complex add, remove, or update logic. ```java proxy.addInterceptor( ProxyInterceptor.builder() .transformingQueryParams(params -> { params.remove("debug"); params.set("format", "json"); if (params.contains("user")) { params.set("user", params.get("user").toLowerCase()); } }) .build() ); ``` -------------------------------- ### Replace Request/Response Body with New Body Instance Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Allows an interceptor to swap the body of a request or response with a new Body instance. Ensure the Content-Type header is set appropriately after replacing the body. ```java import io.vertx.httpproxy.Body; import io.vertx.httpproxy.MediaType; import io.vertx.core.buffer.Buffer; proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyResponse(ProxyContext context) { ProxyResponse resp = context.response(); // Replace body with a static buffer Body newBody = Body.body( Buffer.buffer("{\"status\":\"ok\"}"), MediaType.APPLICATION_JSON ); resp.setBody(newBody); resp.putHeader("content-type", "application/json"); return context.sendResponse(); } }); ``` -------------------------------- ### Enable Interceptor for WebSocket Upgrades Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Make an interceptor available during the WebSocket handshake by using the addInterceptor method with a boolean flag set to true. ```java proxy.addInterceptor(webSocketInterceptorPath, true).listen(); ``` -------------------------------- ### Transform Raw Buffer Response Body Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Applies a custom binary manipulation function to raw buffer response bodies. Use when built-in JSON/text helpers are insufficient. ```java import io.vertx.httpproxy.BodyTransformers; import io.vertx.httpproxy.MediaType; BodyTransformer gzipToRaw = BodyTransformers.transform( MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_OCTET_STREAM, buffer -> { // Custom binary manipulation return buffer; // replace with actual transform } ); proxy.addInterceptor( ProxyInterceptor.builder() .transformingResponseBody(gzipToRaw) .build() ); ``` -------------------------------- ### ForwardedHeadersOptions Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Configures which proxy-identifying headers (e.g., X-Forwarded-For, Forwarded) are appended to upstream requests. It controls the inclusion of client IP, protocol, host, and port information. ```APIDOC ## `ForwardedHeadersOptions` — Forwarded header configuration Controls which proxy-identifying headers (`X-Forwarded-For`, `X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Forwarded-Port`) or the RFC 7239 `Forwarded` header are appended to upstream requests. Disabled by default. ```java import io.vertx.httpproxy.ForwardedHeadersOptions; // Option A: selective X-Forwarded-* headers ForwardedHeadersOptions xForwardedOpts = new ForwardedHeadersOptions() .setEnabled(true) .setForwardFor(true) // adds X-Forwarded-For: .setForwardProto(true) // adds X-Forwarded-Proto: https .setForwardHost(true) // adds X-Forwarded-Host: .setForwardPort(false); // omit X-Forwarded-Port // Option B: RFC 7239 Forwarded header ForwardedHeadersOptions rfc7239Opts = new ForwardedHeadersOptions() .setEnabled(true) .setUseRfc7239(true); // adds: Forwarded: for=;proto=https;host= HttpProxy proxy = HttpProxy.reverseProxy( new ProxyOptions().setForwardedHeadersOptions(rfc7239Opts), proxyClient ); proxy.origin(7070, "origin"); ``` ``` -------------------------------- ### Add ProxyInterceptor for Request/Response Handling Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Append a `ProxyInterceptor` to modify outgoing requests or incoming responses. Interceptors are invoked in order and can handle request and/or response phases. Ensure to call `context.sendRequest()` or `context.sendResponse()` to continue the chain. ```java import io.vertx.httpproxy.ProxyInterceptor; import io.vertx.httpproxy.ProxyContext; import io.vertx.httpproxy.ProxyRequest; import io.vertx.httpproxy.ProxyResponse; proxy.addInterceptor(new ProxyInterceptor() { // Intercept the outgoing request to the origin @Override public Future handleProxyRequest(ProxyContext context) { ProxyRequest req = context.request(); // Add a custom header before forwarding req.headers().set("X-Proxy-Version", "5.x"); req.headers().remove("X-Internal-Secret"); return context.sendRequest(); // continue the chain } // Intercept the response coming back from the origin @Override public Future handleProxyResponse(ProxyContext context) { ProxyResponse resp = context.response(); resp.headers().remove("Server"); // strip origin identity header return context.sendResponse(); // continue the chain } }); ``` -------------------------------- ### Add WebSocket-Aware ProxyInterceptor Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Add an interceptor that also participates in WebSocket upgrade handshakes by setting the second argument to `true`. By default, interceptors are skipped during WebSocket upgrades. ```java ProxyInterceptor interceptor = ProxyInterceptor.builder() .addingPathPrefix("/api") .build(); // true = also apply during WebSocket upgrade requests proxy.addInterceptor(interceptor, true); ``` -------------------------------- ### ProxyRequest.setBody / ProxyResponse.setBody Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Allows an interceptor to swap the body of a request (before sending to origin) or a response (before sending to user-agent) with a new Body instance. ```APIDOC ## ProxyRequest.setBody(Body) / ProxyResponse.setBody(Body) ### Description Allows an interceptor to swap the body of a request (before sending to origin) or a response (before sending to user-agent) with a new `Body` instance. ### Method ```java proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyResponse(ProxyContext context) { ProxyResponse resp = context.response(); // Replace body with a static buffer Body newBody = Body.body( Buffer.buffer("{\"status\":\"ok\"}"), MediaType.APPLICATION_JSON ); resp.setBody(newBody); resp.putHeader("content-type", "application/json"); return context.sendResponse(); } }); ``` ``` -------------------------------- ### ProxyInterceptorBuilder.transformingQueryParams(Handler) — Bulk query param manipulation Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Gives direct access to the full MultiMap of query parameters for complex add/remove/update logic. ```APIDOC ## `ProxyInterceptorBuilder.transformingQueryParams(Handler)` — Bulk query param manipulation Gives direct access to the full `MultiMap` of query parameters for complex add/remove/update logic. ```java proxy.addInterceptor( ProxyInterceptor.builder() .transformingQueryParams(params -> { params.remove("debug"); params.set("format", "json"); if (params.contains("user")) { params.set("user", params.get("user").toLowerCase()); } }) .build() ); ``` ``` -------------------------------- ### Communicate Between Interceptors using Context Payload Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Allows interceptors to attach and retrieve arbitrary data during the request/response lifecycle. Use `context.set(key, value)` to store and `context.get(key, Class)` to retrieve data. ```java proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyRequest(ProxyContext context) { // Store request start time context.set("startTime", System.currentTimeMillis()); return context.sendRequest(); } @Override public Future handleProxyResponse(ProxyContext context) { long start = context.get("startTime", Long.class); long elapsed = System.currentTimeMillis() - start; context.response().headers().set("X-Response-Time", elapsed + "ms"); return context.sendResponse(); } }); ``` -------------------------------- ### HttpProxy.addInterceptor(ProxyInterceptor) — Add an interceptor Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Appends a ProxyInterceptor to the interception chain. Interceptors are invoked in the order they are added. Each interceptor may handle the request phase, the response phase, or both. ```APIDOC ## `HttpProxy.addInterceptor(ProxyInterceptor)` — Add an interceptor Appends a `ProxyInterceptor` to the interception chain. Interceptors are invoked in the order they are added. Each interceptor may handle the request phase, the response phase, or both. ```java import io.vertx.httpproxy.ProxyInterceptor; import io.vertx.httpproxy.ProxyContext; import io.vertx.httpproxy.ProxyRequest; import io.vertx.httpproxy.ProxyResponse; proxy.addInterceptor(new ProxyInterceptor() { // Intercept the outgoing request to the origin @Override public Future handleProxyRequest(ProxyContext context) { ProxyRequest req = context.request(); // Add a custom header before forwarding req.headers().set("X-Proxy-Version", "5.x"); req.headers().remove("X-Internal-Secret"); return context.sendRequest(); // continue the chain } // Intercept the response coming back from the origin @Override public Future handleProxyResponse(ProxyContext context) { ProxyResponse resp = context.response(); resp.headers().remove("Server"); // strip origin identity header return context.sendResponse(); // continue the chain } }); ``` ``` -------------------------------- ### Transform JSON Body with BodyInterceptor Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Utilize predefined transformations for common data types like JsonObject. This transformation is synchronous and buffers bytes. ```java proxy.addInterceptor(bodyInterceptorJson).listen(); ``` -------------------------------- ### Override Request Authority with HostAndPort Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Overrides the Host or :authority header sent to the origin. When overridden, the proxy automatically sets X-Forwarded-Host to the original authority. ```java import io.vertx.core.net.HostAndPort; proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyRequest(ProxyContext context) { // Tell the origin server to treat the request as if it came from example.com:80 context.request().setAuthority(HostAndPort.create("example.com", 80)); return ProxyInterceptor.super.handleProxyRequest(context); } }); ``` -------------------------------- ### Intercept and Modify Request/Response Headers Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Use a ProxyInterceptorBuilder to create an interceptor that modifies request and response headers. Operations are applied in the order of configuration. ```java proxy.addInterceptor(headerInterceptorFilter).listen(); ``` -------------------------------- ### Transform JSON Object Bodies with Default Buffer Limit Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Creates a BodyTransformer that buffers, parses, transforms, and re-serializes JSON object bodies. The default maximum buffered size is 256 KB. ```java import io.vertx.httpproxy.BodyTransformers; proxy.addInterceptor( ProxyInterceptor.builder() .transformingResponseBody( BodyTransformers.jsonObject(json -> { // Remove PII before sending to the user-agent json.remove("ssn"); json.remove("creditCard"); json.put("_proxied", true); return json; }) ) .build() ); ``` -------------------------------- ### HttpProxy.addInterceptor(ProxyInterceptor, boolean) — Interceptor with WebSocket support Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Adds an interceptor that also participates in WebSocket upgrade handshakes when the second argument is true. By default interceptors are skipped during WebSocket upgrades. ```APIDOC ## `HttpProxy.addInterceptor(ProxyInterceptor, boolean)` — Interceptor with WebSocket support Adds an interceptor that also participates in WebSocket upgrade handshakes when the second argument is `true`. By default interceptors are skipped during WebSocket upgrades. ```java ProxyInterceptor interceptor = ProxyInterceptor.builder() .addingPathPrefix("/api") .build(); // true = also apply during WebSocket upgrade requests proxy.addInterceptor(interceptor, true); ``` ``` -------------------------------- ### Override Request Authority Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Manually set the request authority (e.g., Host header) for requests to the origin server. The 'x-forwarded-host' header is automatically set. ```java { // Use examples.HttpProxyExamples#overrideAuthority } ``` -------------------------------- ### Discard Response Body Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Creates a transformer that silently discards the entire response body, regardless of media type. Useful for stripping large or unwanted bodies. ```java proxy.addInterceptor( ProxyInterceptor.builder() .transformingResponseBody(BodyTransformers.discard()) .build() ); ``` -------------------------------- ### Short-Circuit Request with Synthetic Response Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Allows an interceptor to short-circuit the request chain and respond immediately without contacting the origin. Remember to release underlying resources if not proceeding with sendRequest. ```java proxy.addInterceptor(new ProxyInterceptor() { @Override public Future handleProxyRequest(ProxyContext context) { ProxyRequest req = context.request(); // Short-circuit: respond immediately without contacting the origin if ("/health".equals(req.getURI())) { req.release(); // release underlying resources ProxyResponse syntheticResp = req.response() .setStatusCode(200) .putHeader("content-type", "application/json") .setBody(Body.body(Buffer.buffer("{\"status\":\"UP\"}"), MediaType.APPLICATION_JSON)); return Future.succeededFuture(syntheticResp); } return context.sendRequest(); // proceed normally } }); ``` -------------------------------- ### BodyTransformers.text(Function, String) Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Transforms plain-text response bodies by decoding and applying a string manipulation function. This is ideal for modifying text-based content like HTML or plain text. ```APIDOC ## `BodyTransformers.text(Function, String)` — Transform plain-text bodies Buffers, decodes, and transforms a `text/plain` body using a `String -> String` function. ```java import io.vertx.httpproxy.BodyTransformers; proxy.addInterceptor( ProxyInterceptor.builder() .transformingResponseBody( BodyTransformers.text( text -> text.replaceAll("(?i)\\binternal-hostname\\b", "api.example.com"), "UTF-8" ) ) .build() ); ``` ``` -------------------------------- ### ProxyInterceptorBuilder.transformingPath(Function) — Custom path transformation Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Applies an arbitrary function to the request URI before it is forwarded. Multiple calls are applied in order. ```APIDOC ## `ProxyInterceptorBuilder.transformingPath(Function)` — Custom path transformation Applies an arbitrary function to the request URI before it is forwarded. Multiple calls are applied in order. ```java proxy.addInterceptor( ProxyInterceptor.builder() .transformingPath(uri -> uri.replace("/v1/", "/v2/")) // upgrade path version .build() ); ``` ``` -------------------------------- ### Filter Request Body Source: https://github.com/eclipse-vertx/vertx-http-proxy/blob/main/src/main/asciidoc/index.adoc Filter the request body by replacing the original Body object with a new one. ```java proxy.addInterceptor(bodyFilter).listen(); ``` -------------------------------- ### BodyTransformers.discard() Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Creates a transformer that discards the entire response body, regardless of its media type. This is useful for omitting large or unnecessary response payloads. ```APIDOC ## `BodyTransformers.discard()` — Discard the body Creates a transformer that silently discards the entire body, regardless of media type. Useful for stripping large or unwanted response bodies. ```java proxy.addInterceptor( ProxyInterceptor.builder() .transformingResponseBody(BodyTransformers.discard()) .build() ); ``` ``` -------------------------------- ### BodyTransformers.jsonObject(long, Function) Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Like the above, but with an explicit maximum buffered byte count. Useful for large or unbounded responses. ```APIDOC ## BodyTransformers.jsonObject(long, Function) ### Description Like the above, but with an explicit maximum buffered byte count. Useful for large or unbounded responses. ### Method ```java proxy.addInterceptor( ProxyInterceptor.builder() .transformingResponseBody( BodyTransformers.jsonObject( 128 * 1024, // 128 KB limit json -> { json.put("transformed", true); return json; } ) ) .build() ); ``` ``` -------------------------------- ### Transform JSON Object Bodies with Custom Buffer Limit Source: https://context7.com/eclipse-vertx/vertx-http-proxy/llms.txt Transforms JSON object bodies with an explicit maximum buffered byte count. This is useful for handling large or unbounded responses. ```java proxy.addInterceptor( ProxyInterceptor.builder() .transformingResponseBody( BodyTransformers.jsonObject( 128 * 1024, // 128 KB limit json -> { json.put("transformed", true); return json; } ) ) .build() ); ```