Play 允许您直接在 Controller 中返回许多不同的类型,例如 JsValue
或 XML
连同纯文本。我想扩展它以接受 Protocol Buffer ,所以我可以写:
def page = Action {
val protobuf = //...
Ok(protobuf)
}
最佳答案
Java 中的 Protocol Buffer 都继承自一个 com.google.protobuf.Message
类(class)。
在应用程序 Controller 的范围内添加以下隐式转换:
implicit def contentTypeOf_Protobuf: ContentTypeOf[Message] = {
ContentTypeOf[Message](Some("application/x-protobuf"))
}
implicit def writeableOf_Protobuf: Writeable[Message] = {
Writeable[Message](message => message.toByteArray())
}
这些将允许 Play 直接在由状态给出的响应中序列化缓冲区,例如
Ok(protobuf)
更新:
我已经发布了一个相反情况的工作示例,其中可以解析传入的请求并可以自动提取 protobuf。
在这个例子中,解析器采用 Action 的形式,你也可以编写一个正文解析器:
object Put extends Controller {
def index = DecodeProtobuf(classOf[MyProtobuf]) { stack :MyProtobuf =>
Action {
// do something with stack
}
}
}
发送请求的客户端应该将缓冲区序列化为字节数组,并直接在请求正文中传递。
关于scala - 如何直接在 Play 中返回 Protocol Buffer ! 2.0 框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12086132/