Chunked Response handling with Akka Http?

422 views
Skip to first unread message

sub...@gmail.com

unread,
Jan 16, 2017, 10:03:16 AM1/16/17
to Akka User List

I'd like to be able to use akka-http with chunked responses. I'd like to know if I can do the same thing in akka-http as with the playframework. The following is from playframework documentation.


def index = Action {
 val source = Source.apply(List("kiki", "foo", "bar"))
 Ok.chunked(source)
}

We can inspect the HTTP response sent by the server:

HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Transfer-Encoding: chunked

4
kiki
3
foo
3
bar
0


With akka-http I was able to get close with


val hi = Chunk("Hi" + "\n")

val there = Chunk("there" + "\n")

val last = LastChunk("boom" + "\n")


val source: Source[ChunkStreamPart, NotUsed] = Source(scala.collection.immutable.Iterable(hi, there, last))


val rootPath: Route =

  path("") {

    get {

      for (i <- 1 to 100) {

        ref ! hi

      }


      complete(Chunked(ContentTypes.`text/plain(UTF-8)`, source))

    }

  }


def routes: Route = rootPath

}


curl returns


< HTTP/1.1 200 OK

< Server: akka

< Date: Mon, 16 Jan 2017 14:03:10 GMT

< Transfer-Encoding: chunked

< Content-Type: text/plain; charset=UTF-8

<

Hi

there



Two perhaps minor issues: it does not report the last element, and it doesn't include the chunk size as the playframework example did.


What I’d like to know is how can I do this in a dynamic way? I'm interacting with a embedded device (via serial) where I make an async request and it responds one or more times up to about 20 seconds. I'd like each response to be emitted as a chunk. Is this possible?


Thanks,

Andrew

Akka Team

unread,
Feb 1, 2017, 5:25:41 PM2/1/17
to Akka User List
This is definitely possible, just use Chunk for each element instead, that way you can create them from a stream of strings using .map()

For the "an async request and it responds one or more times" there are a few possible tools in Akka streams that may solve this. Take a look at Source.unfoldAsync, Source.unfoldResourceAsync and Source.queue and see if either of those fit your use case.

-- 
Johan
Akka Team

--
>>>>>>>>>> Read the docs: http://akka.io/docs/
>>>>>>>>>> Check the FAQ: http://doc.akka.io/docs/akka/current/additional/faq.html
>>>>>>>>>> Search the archives: https://groups.google.com/group/akka-user
---
You received this message because you are subscribed to the Google Groups "Akka User List" group.
To unsubscribe from this group and stop receiving emails from it, send an email to akka-user+unsubscribe@googlegroups.com.
To post to this group, send email to akka...@googlegroups.com.
Visit this group at https://groups.google.com/group/akka-user.
For more options, visit https://groups.google.com/d/optout.




Reply all
Reply to author
Forward
0 new messages