Skip to content

Instantly share code, notes, and snippets.

@johanandren
Created October 13, 2017 14:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanandren/ab4b2df05004399298e900776690a0de to your computer and use it in GitHub Desktop.
Save johanandren/ab4b2df05004399298e900776690a0de to your computer and use it in GitHub Desktop.
Combining multiple unmarshallers for different dataformats for one path
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ContentTypes
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.stream.ActorMaterializer
object MultipleUnmarshallers extends App {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
import system.dispatcher
case class Thing(n: Int)
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
val jsonUnmarshaller: FromEntityUnmarshaller[Thing] = jsonFormat1(Thing)
val textUnmarshaller: FromEntityUnmarshaller[Thing] =
Unmarshaller.stringUnmarshaller.map(str => Thing(str.toInt))
.forContentTypes(ContentTypes.`text/plain(UTF-8)`)
implicit val combined: FromEntityUnmarshaller[Thing] =
Unmarshaller.firstOf(jsonUnmarshaller, textUnmarshaller)
import akka.http.scaladsl.server.Directives._
val route =
post {
entity(as[Thing]) { thing =>
complete("Ok" + thing)
}
}
Http().bindAndHandle(route, "127.0.0.1", 8080).onComplete(println)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment