Akka http - dispatch on request content type

36 views
Skip to first unread message

kr...@humio.com

unread,
Oct 9, 2017, 3:45:08 PM10/9/17
to Akka User List
Hi,

I've been trying to find an example that illustrates how to write a route that follows different paths based on the Content-Type of a request.

Clearly, I can extract the value of the "Content-Type" header, but then there is the charset and everything to worry about in the resulting value.

Basically I want to have a post { ... } rule, that do three different things if the incoming data is text/plain (split it by newlines), application/json (parse it as such). In both cases I would want to unmarshall the data in the charset given by the client.  A third rule would match the binary type application/x-vnd-foo would parse the incoming data from ByteString.

So how do I use all the akka niceties to write this "case statement" with 3 different part-routes without having to extract and match the strings?

The world seems to be full of examples of how to match 'Accept' rules to response content types in akka, but nothing easy to find on the incoming case.

Thanks,

Kresten

Johan Andrén

unread,
Oct 13, 2017, 11:06:26 AM10/13/17
to Akka User List
The "normal" way would be to have the same logic, but different unmarshalling, and this the unmarshalling infra takes care of, you'd use the entity directive https://doc.akka.io/docs/akka-http/10.0.10/scala/http/routing-dsl/directives/marshalling-directives/entity.html and pass a super-marshaller created by passing the supported marshalers to `Unmarshalling.firstOf(json, text, binary)`. This isn't super obvious from the docs so there are some possible improvements here.

Here is a working sample that does exactly this: https://gist.github.com/johanandren/ab4b2df05004399298e900776690a0de

If you are not interested in this but actually want different logic to happen depending on the content type, then extracting the content type and matching is probably the way to go, note that you should still be able to make use of the unmarshalling infra for the individual sub-routes to get character encoding automagically handled.

--
Johan
Akka Team
Reply all
Reply to author
Forward
0 new messages