https://kotlinlang.org logo
#http4k
Title
# http4k
n

Nezteb

04/22/2019, 9:31 PM
i’m trying a simple echo handler basically that just returns the request it received as JSON in the body. I assume I need
.body
, not
.with
, but how can I convert the request to JSON? I could use a Jackson mapper manually, but I assume HTTP4k has a built-in way to do it
Copy code
fun getRequestAsJson(): HttpHandler {
    return {
        Response(OK).body(it)
    }
}
✔️ 1
s

s4nchez

04/22/2019, 9:33 PM
What do you mean by "covert the request to JSON"? Can you provide an example on how you'd like the response to look like?
n

Nezteb

04/22/2019, 9:36 PM
The method, uri, all the headers, all the query params, etc. Which are encapsulated in the object. In javalin for example, you can just do
jacksonMapper.readValue(request)
and put it in the response body
Sweet, so I got that working, but the response header is always
Content-Type →application/octet-stream
1. i assume it should default to JSON, since i’m not setting that anywhere 2. how can I change it? Via filter? Filters can operate on requests, but maybe not responses?
s

s4nchez

04/22/2019, 10:44 PM
If you just want to print the request in the response, you can do
Response(OK).body(request.toString())
. The string versions of request and response are similar to what is sent over the wire
To set the response content-type you can either do
Response(OK).header("content-type", "application/json")
or, using Lens via
Response(OK).with(Header.CONTENT_TYPE of ContentType.APPLICATION_JSON
n

Nezteb

04/22/2019, 10:47 PM
Copy code
fun health(): HttpHandler {
    return {
        Response(OK).body("I'm healthy!")
    }
}
the header here defaults to
octet-stream
every time.
if i manually set the header it’s fine, but
octet-stream
seems like an odd default
ooo good call with the
.with(Header...
bit, thanks~
s

s4nchez

04/22/2019, 10:49 PM
The
octet-stream
is not our default. It's probably the backend you're using or what the browser or client assumes if the server sends none.
n

Nezteb

04/22/2019, 10:50 PM
hmmmm, i’ll investigate. i’m using KtorCIO
3 Views