A running server in one file.
One main function - start a server, call it with an http4k client, print the response, stop. Copy it, run it, no build wizard required.
Add the dependencies
http4k-core, an Undertow server backend and the Apache HTTP client - the three modules this example uses.
dependencies {
implementation(platform("org.http4k:http4k-bom:6.61.0.0"))
implementation("org.http4k:http4k-core")
implementation("org.http4k:http4k-server-undertow")
implementation("org.http4k:http4k-client-apache")
}Write your app
A handler is a function. This main starts it on a server, calls it with an http4k client, prints the response and shuts down.
import org.http4k.client.ApacheClient
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.server.Undertow
import org.http4k.server.asServer
fun main() {
val app = { request: Request -> Response(OK).body("Hello, ${request.query("name")}!") }
val server = app.asServer(Undertow(9000)).start()
val client = ApacheClient()
val request = Request(Method.GET, "http://localhost:9000").query("name", "John Doe")
println(client(request))
server.stop()
}
Run it
Hit the green run arrow next to main in your IDE - it's an ordinary Kotlin main, no run task to configure. You'll see the response printed to the console.
HTTP/1.1 200 OK
Hello, John Doe!And because your app is just a function, exercising it in a test never needs a running server. That's the whole model - everything else in http4k composes from exactly this.
