如何在播放中直接返回协议缓冲区!2.0框架



Play允许您直接在控制器中返回许多不同的类型,如JsValueXML以及纯文本。我想把它扩展到接受协议缓冲区,这样我就可以写:

def page = Action {
    val protobuf = //...
    Ok(protobuf)
}
Java中的协议缓冲区都继承自单个com.google.protobuf.Message类。

在应用程序控制器的范围内添加以下隐式转换:

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。

  • https://gist.github.com/3455432

在这个例子中,解析器采用了一个动作的形式,尽管你也可以编写一个主体解析器:

object Put extends Controller {
  def index = DecodeProtobuf(classOf[MyProtobuf]) { stack :MyProtobuf =>
    Action {
      // do something with stack
    }
  }
}

发送请求的客户端应该将缓冲区序列化为字节数组,并将其直接传递到请求的主体中。

最新更新