Scala 的 HTTP 服务接口:http4s
http4s是最小的,符合语言习惯的Scala的HTTP服务接口。可以把http4s想象成Ruby 的 Rack、Python 的 WSGI、Haskell 的 WAI 和 Java 的 Servlet。
</div>
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 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!