i’m trying a simple echo handler basically that ju...
# http4k
n
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
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
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
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
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
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
hmmmm, i’ll investigate. i’m using KtorCIO