Created
October 13, 2017 14:56
-
-
Save johanandren/ab4b2df05004399298e900776690a0de to your computer and use it in GitHub Desktop.
Combining multiple unmarshallers for different dataformats for one path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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