Skip to content

Instantly share code, notes, and snippets.

@rwalk
Last active February 22, 2022 16:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwalk/3b4dc9524b2383a9645d3d88a2e820d9 to your computer and use it in GitHub Desktop.
Save rwalk/3b4dc9524b2383a9645d3d88a2e820d9 to your computer and use it in GitHub Desktop.
Scalatra: chunked transfer Encoding HTTP endpoint example
#
# a simple client for the endpoint.
#
import requests
import time
r = requests.get("http://localhost:8080/chunks", stream=True)
t0 = time.time()
for message in r.iter_lines(chunk_size=1):
print("At %d s, recieved: %s" % (time.time()-t0, message.decode("utf-8")))
import org.json4s.{DefaultFormats, Formats}
import scala.language.postfixOps
import scalate.ScalateSupport
import org.scalatra._
import java.io.PrintWriter
class Chunks extends ScalatraServlet with ScalateSupport {
/*
Simple example of chunked transfer encoding in Scalatra (scala web framework)
*/
get("/") {
response.setHeader("Content-Type", "text/html")
response.setHeader("Transfer-Encoding", "chunked")
response.setStatus(200)
val out = response.getWriter
0 to 100 foreach { i=>
sendMessage(s"Hello! This is message $i.", out)
Thread.sleep(1000)
}
}
def sendMessage(message:String, output:PrintWriter): Unit = {
output.println(message)
output.flush()
println("SENT: " + message)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment