Skip to content

Instantly share code, notes, and snippets.

@rodrigopr
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigopr/db671a7644e5d2f2e244 to your computer and use it in GitHub Desktop.
Save rodrigopr/db671a7644e5d2f2e244 to your computer and use it in GitHub Desktop.
class FormatEncoder[Encoder <: EncodeResponse[_]] {
def encoder[A]: Encoder[A] = implicitly[Encoder[A]] // implicit encode must be in scope =/
}
class Formats(encoders: (String, FormatEncoder[_])*, defaultFormat: String) {
private val formatsHash = encoders.toMap
private val default = formatsHash(defaultFormat)
def encodeFor[A](httpReq: HttpRequest): EncodeResponse[A] = formatsHash.getOrElse(???, default).encoder[A]
}
val formats = new Formats (
"application/json" -> FormatEncoder[EncodeJson],
"application/xml" -> FormatEncoder[EncodeXml]
)
def hello(name: String) = new Service[HttpRequest, HttpResponse] {
def apply(req: HttpRequest) = for {
title <- OptionalParam("title")(req)
} yield Ok(Response(...))(formats.encodeFor(req))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment