Skip to content

Instantly share code, notes, and snippets.

@razvn
Last active April 16, 2021 17:00
Show Gist options
  • Save razvn/b8dfc1a3db6496c465d0efac5ba4056b to your computer and use it in GitHub Desktop.
Save razvn/b8dfc1a3db6496c465d0efac5ba4056b to your computer and use it in GitHub Desktop.
http4k endpoint that makes the call to another url and return the response
// all calls on `$path` are redirected to `$url`
// ex: server `http://localport:8080` call `MocksRoute("http://google.com", "proxy")`
// all calls to `http://localport:8080/proxy/<whatever>` will respond with the response of `http://google.com/<whatever>`
// query params and headers are forwarded
object MocksRoute {
private val pathLens = Path.string().of("reqpath")
operator fun invoke(url: String, path: String = "", client: HttpHandler = OkHttp()): RoutingHttpHandler =
routes("/$path/{reqpath:.*}" bind handler(url, client))
private fun handler(url: String, client: HttpHandler): HttpHandler = { req ->
val baseNewUri = Uri.of("$url/${pathLens(req).removePrefix("/")}")
val newUri = req.uri.copy(
scheme = baseNewUri.scheme,
host = baseNewUri.host,
port = baseNewUri.port,
path = baseNewUri.path
)
client(req.uri(newUri)).removeHeader("Content-Length")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment