Skip to content

Instantly share code, notes, and snippets.

@groundwater
Created August 24, 2012 20:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groundwater/3455432 to your computer and use it in GitHub Desktop.
Save groundwater/3455432 to your computer and use it in GitHub Desktop.
Action that parses protocol buffers
object Put extends Controller {
def index = DecodeProtobuf(classOf[MyProtobuf]) { stack :MyProtobuf =>
Action {
// do something with stack
}
}
}
trait DecodeProtobuf[P <: Message, A] extends Action[A]
object DecodeProtobuf {
def base64decode(code: String) = new sun.misc.BASE64Decoder().decodeBuffer(code)
def apply[P <: Message, A](bodyParser: BodyParser[A], proto: Class[P])(block: P => Request[A] => Result) = new DecodeProtobuf[P, A] {
def parser = bodyParser
def apply(req: Request[A]) = {
req.body.asInstanceOf[AnyContent].asRaw.flatMap { raw =>
raw.asBytes().map { bytes =>
try {
val parseFrom = proto.getMethod("parseFrom", classOf[Array[Byte]])
val message: P = parseFrom.invoke(proto, bytes).asInstanceOf[P]
block(message)(req)
}catch{
case e:NoSuchMethodException => Results.BadRequest
}
}
}
} getOrElse { Results.InternalServerError }
}
def apply[P <: Message](proto: Class[P])(block: P => Request[AnyContent] => Result): Action[AnyContent] = {
DecodeProtobuf(BodyParsers.parse.anyContent, proto)(block)
}
}
@pcejrowski
Copy link

Could you pass an example of protoc-curl combination to query this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment