Skip to content

Instantly share code, notes, and snippets.

View s1monw1's full-sized avatar
☁️
Hello, cloud.

Simon Wirtz s1monw1

☁️
Hello, cloud.
View GitHub Profile
class PrintingCustomizer { // PrintingCustomizer is a dispatch receiver
private val separator = "________________"
fun <K, V> Map<K, V>.customPrint() { // Map<T, V> is an extension receiver for customPrint
forEach { (k, v) ->
println("K: $k")
println("V: $v")
println(separator)
}
}
class PrintingCustomizer {
private val separator = "________________"
fun <T, V> Map<T, V>.customPrint() {
forEach { (k, v) ->
println("K: $k")
println("V: $v")
println(separator)
}
}
val request = Request(Method.GET, "https://kotlinexpertise.com/sitemap.xml")
val client: HttpHandler = JavaHttpClient()
val response = client(request)
val addExtraHeaderFilter = Filter { next ->
{
next(it).header("x-extra-header", "some value")
}
}
@Test
fun adds_a_special_header() {
val handler: HttpHandler = addExtraHeaderFilter.then { Response(OK) }
val response: Response = handler(Request(GET, "/echo"))
import com.natpryce.hamkrest.assertion.assertThat
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Status
import org.http4k.hamkrest.hasStatus
import org.junit.jupiter.api.Test
class PersonHandlerProviderTest {
val systemUnderTest = PersonHandlerProvider(PersonService())
[...]
import org.http4k.format.Jackson.auto
class PersonHandlerProvider(private val service: PersonService) {
private val personLens: BiDiBodyLens<Person> = Body.auto<Person>().toLens()
private val personListLens: BiDiBodyLens<List<Person>> = Body.auto<List<Person>>().toLens()
fun getAllHandler(): HttpHandler = {
Response(OK).with(
personListLens of service.findAll()
)
val req = Request(GET, "/greet/{name}")
val reqWithName = nameLens.inject("kotlin", req)
// alternatively, http4k offers a with function that can apply multiple lenses at once
val reqWithName = Request(GET, "/greet/{name}").with(
nameLens of "simon" //, more lenses
)
// gzip omitted
val app: HttpHandler = ServerFilters.CatchLensFailure
.then(requestTimeLogger)
.then(routing)
val nameLens: BiDiLens<Request, String> =
Query.nonEmptyString().required("name")
val greetHandler: HttpHandler = { req: Request ->
val name: String = nameLens.extract(req) //or nameLens(req)
Response(OK).body("hello $name")
}
// lens focusing on the path variable name
val nameLens = Path.string().of("name")
// lens focusing on a required query parameter city
val requiredQuery = Query.required("city")
// lens focusing on a required and non-empty string city
val nonEmptyQuery = Query.nonEmptyString().required("city")
// lens focusing on an optional header Content-Length with type int