LoginSignup
3
1

More than 5 years have passed since last update.

FinagleでWebAPIサーバを立てる

Last updated at Posted at 2016-08-27

概要

(「フィネーグル」って読んでるけど、正しくは「フィネーフル」なんですか?)

ちょっと仕事で簡単なWebAPIサーバー立てることになったのでfinagle-httpを試した。
結局その後色々あってplay2に変えてしまいましたが。。

その時に調べたら、全然情報がなかったので簡単にメモ。
WebAPI用途ならsprayとかakka-httpの方が人気なんだろうか。。
akka-httpはいつexperimental取れるんだろうか。。

ゴール

  • finagle-httpでパスに応じて処理を切り分ける。
  • headerとかcookieとかいじる

コード

build.sbt
libraryDependencies ++= Seq(
      "com.twitter" %% "finagle-netty4-http" % "6.37.0"
    )

finagle-httpはnetty3だったのでなんとなくこっち使ってみた。

Main.scala
import com.twitter.finagle.http.service.RoutingService
import com.twitter.finagle.http.{Cookie, Request, Response}
import com.twitter.finagle.{Http, Service, http}
import com.twitter.util.{Await, Future}

object Main {

  def main (args: Array[String] ): Unit = {

    val index = new Service[Request, Response] {
      def apply(request: http.Request): Future[http.Response] = {
        val res = http.Response(request.version, http.Status.Ok)
        res.setContentString("Ok")
        Future.value(res)
      }
    }

    def execute(userId: String, num: Int) = new Service[Request, Response] {

      def apply(request: Request): Future[http.Response] = {
        val resultString = s"user id: ${userId}. num: ${num}"
        val res = http.Response(request.version, http.Status.Ok)
        res.setContentString(resultString)

        val cookie = new Cookie("key", "value")
        cookie.httpOnly_=(true)
        res.addCookie(cookie)

        res.setContentType("text/plain")

        Future.value(res)
      }
    }

    import com.twitter.finagle.http.path._
    val router = RoutingService.byPathObject[Request] {
      case Root / "userId" / userId / "number" / Integer(num) => execute(userId, num)
      case Root / "userId" => execute("uuu", 3)
      case _                             => index
    }

    val server = Http.serve(":9999", router)
    Await.ready(server)
  }

}
$ curl --verbose http://localhost:9999/userId/uu/number/100
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9999 (#0)
> GET /userId/uu/number/100 HTTP/1.1
> Host: localhost:9999
> User-Agent: curl/7.45.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Set-Cookie: key=value; HTTPOnly
< Content-Type: text/plain;charset=utf-8
< Content-Length: 21
< 
* Connection #0 to host localhost left intact
user id: uu. num: 100

まとめ

routingのとこ、ソースコード読まないとわかんなかった。
ドキュメントシンプル過ぎてよくわかんない

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1