Skip to content

Instantly share code, notes, and snippets.

@tobnee
Last active December 11, 2015 11:28
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 tobnee/4594246 to your computer and use it in GitHub Desktop.
Save tobnee/4594246 to your computer and use it in GitHub Desktop.
Play2 based content negotiation
import play.api.mvc._
import play.api.mvc.Results._
import play.api.http.MimeTypes._
def resource() = Action { implicit request =>
negotiate(
HTML ->
(() => Ok("html")),
JSON ->
(() => Ok("json")),
XML ->
(() => Ok("xml"))
)
}
def negotiate(handles: (String, () => Result)*)(implicit request: Request[_]): Result = {
val handleMap = handles.toMap
val handleValues = handles.map(_._1)
val matchingType = request.acceptedTypes.
foldLeft(None.asInstanceOf[Option[String]]) {
(resultType, preferredType) =>
if (resultType.isDefined) resultType
else {
handleValues.dropWhile(handle => !preferredType.accepts(handle)).headOption
}
}
matchingType.map(mType => handleMap(mType).apply()).getOrElse(NotAcceptable)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment