【问题标题】:Scala Post method in Finch with double colon带有双冒号的 Finch 中的 Scala Post 方法
【发布时间】:2018-10-16 15:57:00
【问题描述】:

我在继承的遗留系统中无法读取这行 scala。

post("tokens" :: Auth() :: stringBody) { (_: String, token: String) =>

如果需要,我可以在之前和之后发布这些行,但我认为这行本身对 Scala 开发人员有一定的意义。

post方法来自finch库,这里是方法签名和注释:

/**
   * A combinator that wraps the given [[Endpoint]] with additional check of the HTTP method. The
   * resulting [[Endpoint]] succeeds on the request only if its method is `POST` and the underlying
   * endpoint succeeds on it.
   */
  def post[A](e: Endpoint[A]): EndpointMapper[A] = new EndpointMapper[A](Method.Post, e)

我假设下划线是一个字符串的全部匹配,但是这个匹配是什么?我假设它与 post 方法中的参数匹配,但是捕获了三个参数和两个东西。

我假设该方法与“令牌”REST 端点值匹配,然后需要一个 Auth 标头并捕获字符串正文。我对双冒号参数在这种情况下的含义感到困惑,因为它在第一次和第二次使用时会表现不同。

【问题讨论】:

  • post 方法的签名是什么?在这种情况下,下划线表示函数的忽略参数。 { (_: Int, token: String) => 部分是一个以两个字符串作为输入的 lambda 函数的开头。
  • 我会用方法的签名和注释更新问题
  • 已更新,感谢评论

标签: scala post


【解决方案1】:

当您发布指向finch 的链接时,它是用于finagle http 服务的组合API。

  • 您将 finch 端点组合为 pathparamheadercookiebody 等的组合。请参阅代码库 here
  • 您使用:: 运算符组合端点

Endpoint#::has a definition as below

final def ::[B](other: Endpoint[B])(implicit pa: PairAdjoin[B, A]): Endpoint[pa.Out]

因此,在您的示例中,您必须使用path、可能是header 和请求body 组成端点。而{} 块是您的端点成功。由于您正在编写headerbody,因此可以考虑输出两个结果。在scala中如果你不打算使用变量,你可以discard naming it with _

例如,List(1, 2).map(elem => elem * 2) 等价于 List(1, 2).map(_ * 2)

芬奇端点示例,

  val auth = post("tokens" :: header[String]("auth") :: stringBody) {
    (authHeader: String, body: String) =>
      Ok(s"""
         {
            "auth": "$authHeader",
            "body": "$body"
         }
       """.stripMargin)
  }

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

    val endpoints: Service[Request, Response] = auth.toService

    Await.ready(Http.server.serve(":9090", endpoints))

  }

一旦你运行它,你就可以使用端点来使用

$ curl --request POST -H "auth: some header" -d "some data" localhost:9090/tokens
"\n         {\n            \"auth\": \"some header\",\n            \"body\": \"some data\"\n         }\n       "

【讨论】:

  • 非常感谢您的回答,现在通读,然后将根据需要进行投票/标记
猜你喜欢
  • 2017-04-17
  • 2019-09-14
  • 1970-01-01
  • 2014-12-27
  • 1970-01-01
  • 2018-01-01
  • 2015-08-18
  • 1970-01-01
  • 2011-08-11
相关资源
最近更新 更多