gpt4 book ai didi

web-services - 如何在 Finch 中绑定(bind)请求正文

转载 作者:行者123 更新时间:2023-12-04 11:21:26 25 4
gpt4 key购买 nike

这是将请求参数绑定(bind)到路由器的代码。

val testReader: Endpoint[Test] = Endpoint.derive[Test].fromParams
val test: Endpoint[String] = post("test" ? testReader) { t : Test => {
Created("OK")
}}

我使用的方法是 fromParams .这个方法可以很酷的绑定(bind)请求参数。但是,我不知道我可以用哪种类似的方式绑定(bind) 请求正文 在雀科

提前谢谢了

最佳答案

为了提供一个完整的工作示例,我将假设一个这样的案例类:

case class Test(foo: Int, bar: String)

还有一些这样的请求:
import com.twitter.finagle.http.{ Method, Request, RequestBuilder }
import com.twitter.io.{ Buf, Reader }

val queryParamPost = Request(Method.Post, "/test?foo=1&bar=whatever")

val testJsonBuf = Buf.Utf8("""{ "foo": 1, "bar": "whatever" }""")

val bodyPost = RequestBuilder().url("http://localhost:8080/test").buildPost(testJsonBuf)

现在,当您编写以下内容时……
import io.finch._

val testParams: Endpoint[Test] = Endpoint.derive[Test].fromParams
val test: Endpoint[Test] = post("test" ? testParams) { test: Test =>
Created(test)
}

发生的事情是 Finch 使用泛型派生(由 Shapeless 提供支持)来确定(在编译时)如何将查询参数解析为 Test .然后,您可以像这样测试端点:
import io.finch.circe._
import io.circe.generic.auto._

test.toService.apply(queryParamPost).onSuccess { response =>
println(s"$response: ${ response.contentString }")
}

这将打印:
Response("HTTP/1.1 Status(201)"): {"foo":1,"bar":"whatever"}

这里我使用 Circe的通用派生自动编码“创建” Test作为响应的 JSON。

您还可以使用 Circe 为请求正文派生一个阅读器:
val testBody: Endpoint[Test] = body.as[Test]
val test2: Endpoint[Test] = post("test" :: testBody) { test: Test =>
Created(test)
}

这与 test 几乎完全相同。上面,但我们使用的是 body获取 Endpoint[String]这将读取请求正文,然后 as指定我们希望将内容解析为 JSON 并解码为 Test值(value)。我们可以像这样测试这个新版本:
test2.toService.apply(bodyPost).onSuccess { response =>
println(s"$response: ${ response.contentString }")
}

我们将再次得到我们期望的答案。

通常,当您想读取传入请求的某种信息时,您将使用基本的 Endpoint 之一。 s 由 Finch 提供(参见 the docs 以获得更完整的列表),然后使用像 as 这样的方法, map等关于 Endpoint把它变成你需要的形状。

关于web-services - 如何在 Finch 中绑定(bind)请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36966835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com