Last active
February 22, 2022 16:23
-
-
Save rwalk/3b4dc9524b2383a9645d3d88a2e820d9 to your computer and use it in GitHub Desktop.
Scalatra: chunked transfer Encoding HTTP endpoint example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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"))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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