Reverse Proxies

The reverse proxy content provider allows to embed content from another web server into your application.

Kotlin
val proxy = Proxy.create()
    .upstream("http://my-cdn:8080/")

Host.create()
    .handler(proxy)
    .run()

When running this example, any request to http://localhost:8080 will be proxied to http://my-cdn:8080/. Proxying works both for regular HTTP requests and websocket connections.

If the upstream server is either not available or does not respond in time, the provider will return an HTTP 502/504 error page instead. The time allowed to connect to the upstream server (10 seconds by default) and to receive its response (60 seconds by default) can be adjusted:

Kotlin
val proxy = Proxy.create()
    .upstream("http://my-cdn:8080/")
    .connectTimeout(5.seconds)
    .readTimeout(2.minutes)

Adjustments

The module internally uses the java.net.http.HttpClient of the JDK to perform HTTP requests. If needed, you can pass functions to adjust the client as required.

Kotlin
import java.net.http.HttpClient

import org.genhttp.modules.reverseproxy.Proxy

val proxy = Proxy.create()
    .upstream("http://my-cdn:8080/")
    .adjustHandler { builder -> builder.proxy(HttpClient.Builder.NO_PROXY) }
    .adjustClient { client -> println("Proxying via ${client.version()}") }

GenHTTP configures a SocketsHttpHandler and an HttpClient of .NET here. The client of the JDK is immutable and configured through its builder instead: adjustHandler receives the HttpClient.Builder before the client is created (to set a proxy, an SSLContext or an executor), adjustClient the client after it has been created.