Scala 的 HTTP 服務接口:http4s
http4s是最小的,</span>符合語言習慣</span>的Scala</span>的</span>HTTP服務</span>接口</span>。</span>可以把http4s想象成Ruby 的 Rack、Python 的 WSGI、Haskell 的 WAI 和 Java 的 Servlet。
Asynchronous
任何http4s響應可以從異步源進行流式處理。http4s提供多種助手來幫助你,以最快的方式得到你的數據。
// Make your model safe and streaming by using a scalaz-stream Process
def getData(req: Request): Process[Task, String] = ???
val service: HttpService = {
// Wire your data into your service
case GET -> Root / "streaming" => Ok(getData(req))
// You can use helpers to send any type of data with an available Writable[T]
case GET -> Root / "synchronous" => Ok("This is good to go right now.")
}
http4s is a forward-looking technology. HTTP/2.0 and WebSockets will play a central role.
val route: HttpService = {
case req@ GET -> Root / "ws" =>
// Send a Text message with payload 'Ping!' every second
val src = Process.awakeEvery(1.seconds).map{ d => Text(s"Ping! $d") }
// Print received Text frames, and, on completion, notify the console
val sink: Sink[Task, WSFrame] = Process.constant {
case Text(t) => Task.delay(println(t))
case f => Task.delay(println(s"Unknown type: $f"))
}.onComplete(Process.eval(Task{ println("Terminated!")}).drain)
// Use the WS helper to make the Task[Response] carrying the info
// needed for the backend to upgrade to a WebSocket connection
WS(src, sink)
case req @ GET -> Root / "wsecho" =>
// a scalaz topic acts as a hub to publish and subscribe to messages safely
val t = topic[WSFrame]
val src = t.subscribe.collect{ case Text(msg) => Text("You sent the server: " + msg) }
WS(src, t.publish)
}
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!