Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

scala - Akka-http - write to response output stream

I need to create a large tab separated file as a response to HTTP GET request. In my route a create some Scala objects and then I want to write some custom representation of those objects to the Output Stream.

It is not just serialization to tab separated instead of JSON, because I need also to create a header with column names, so IMHO this can't be solved with custom marshaling.

So how can I get a writer or outputstream from HttpRequest?

Something like

 ~path("export") {
        get {
              val sampleExonRPKMs = exonRPKMService.getRPKMs(samples)
              val writer = HttpResponse().getWriter // this does not exists
              writeHeader(writer)
              ... // write objects tab separated
        }
   }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can complete an Akka HTTP route with a marshallable source. If you don't want to use custom marshallers, you can always complete with a Source[ByteString, _]. See the docs for more info.

Your route will look something like

get {
  val sampleExonRPKMs = exonRPKMService.getRPKMs(samples)
  val headers: String = ???
  Source.single(headers).concat(Source(sampleExonRPKMs).map(_.toTSVLine)).intersperse("
").map(ByteString.apply)
}

Note as a separate issue: if you are dealing with large amounts of data, the getRPKMs call will result in loading all of it in memory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...