Scala 的 HTTP 服务接口:http4s

jopen 10年前

http4s是最小的符合语言习惯的ScalaHTTP服务接口可以把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)  }
</div>

项目主页:http://www.open-open.com/lib/view/home/1410752875555