1
votes

I would like to know how to create my own body parser in scala and play framework. In general, my use case is to create a body parser that would accept a chunked stream from a client and for each chunk it would perform some action (rather then accumulating the whole data and do something in the end).

Since I couldn't find any documentation regarding this topic I would appreciate any code examples or link that would explain this.

1

1 Answers

1
votes

When you say "chunked", do you mean chunked at the HTTP protocol level, as in Transfer-Encoding: chunked? While you can work on "chunks" of data, in Play these do not necessarily correlate 1 to 1 with chunks in chunked encoding. In fact, you should never rely on the demarcation of these chunks, as it's completely legal for any proxy to dechunk it, or rechunk it at different lengths. So, you should ensure that whatever protocol is in the chunks is able to indicate the start and end of your logical chunks of data, regardless of how the underlying stream is actually encoded, accounting for the fact that each actual chunk that your code receives may contain multiple logical chunks, partial logical chunks, or both.

So, with that understanding, to parse your data, you'll need to write an iteratee. A Play BodyParser is essentially a function that takes a RequestHeader, and returns an Iteratee[Array[Byte], B], which parses a body of type B. I wrote a blog post that explains iteratees here:

http://jazzy.id.au/default/2012/11/06/iteratees_for_imperative_programmers.html

An example of a protocol that you might use to demarcate your chunks might be JSON, there's a blog post here about how to actually do this with JSON:

http://manuel.bernhardt.io/2013/10/21/reactive-golf-or-iteratees-and-all-that-stuff-in-practice-part-2/