Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
39 lines (28 sloc) 1.28 KB
package guide.modules.message_formats
import org.http4k.core.Body
import org.http4k.core.Method.GET
import org.http4k.core.Request
data class Email(val value: String)
data class Message(val subject: String, val from: Email, val to: Email)
fun main() {
// We can use the auto method here from either Jackson, Gson or the Xml message format objects.
// Note that the auto() method needs to be manually imported as IntelliJ won't pick it up automatically.
val messageLens =<Message>().toLens()
val myMessage = Message("hello", Email(""), Email(""))
// to inject the body into the message - this also works with Response
val requestWithEmail = messageLens.inject(myMessage, Request(GET, "/"))
// Produces:
// GET / HTTP/1.1
// content-type: application/json
// {"subject":"hello","from":{"value":""},"to":{"value":""}}
// to extract the body from the message - this also works with Response
val extractedMessage = messageLens.extract(requestWithEmail)
println(extractedMessage == myMessage)
// Produces:
// Message(subject=hello, from=Email(, to=Email(
// true