How Can I Return Protocol Buffers Directly in Play! 2.0 Framework?
playframework-2.0, protocol-buffers, scala
Solution
Protocol buffers in Java all inherit from a single `com.google.protobuf.Message` class.
Add the following implicit conversions within the scope of your application controller:
implicit def contentTypeOf_Protobuf: ContentTypeOf[Message] = {
ContentTypeOf[Message](Some("application/x-protobuf"))
}
implicit def writeableOf_Protobuf: Writeable[Message] = {
Writeable[Message](message => message.toByteArray())
}
These will allow Play to serialize buffers directly in a response given by a status such as `Ok(protobuf)`
Update:
I have posted a working example of the reverse situation, where the incoming request can be parsed and a protobuf can be extracted automatically.
- https://gist.github.com/3455432
The parser takes the form of an action in this example, tho you could also code a body parser:
object Put extends Controller {
def index = DecodeProtobuf(classOf[MyProtobuf]) { stack :MyProtobuf =>
Action {
// do something with stack
}
}
}
The client sending the request should serialize the buffer as a byte array, and pass it directly in the body of the request.
Problem
Play lets you return a number of different types directly in your controllers, such as `JsValue` or `XML` along with plain text. I would like to extend this to accept protocol buffers, so I can write: ``` def page = Action { val protobuf = //... Ok(protobuf) } ```