这是将请求参数绑定到路由器的代码。
val testReader: Endpoint[Test] = Endpoint.derive[Test].fromParams
val test: Endpoint[String] = post("test" ? testReader) { t : Test => {
Created("OK")
}}
我正在使用该方法fromParams
。该方法可以以非常酷的方式绑定请求参数。但是,我不知道我可以在雀科中绑定请求正文的哪种相似方式
提前谢谢了
为了提供一个完整的工作示例,我将假设一个case类,如下所示:
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支持)确定(在编译时)如何将查询参数解析为a 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
值。我们可以像这样测试这个新版本:
test2.toService.apply(bodyPost).onSuccess { response =>
println(s"$response: ${ response.contentString }")
}
我们将再次得到我们期望的答案。
通常,当你想读某一种传入的请求的信息,您可以使用基本的一个Endpoint
由芬奇提供S(参见该文档的完整列表),然后用类似的方法as
,map
等上在Endpoint
把它变成你所需要的形状。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句