Last active
April 16, 2021 17:00
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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