Created
April 5, 2014 12:32
-
-
Save davidmweber/9991408 to your computer and use it in GitHub Desktop.
Unmarshal http request data depending on media type
This file contains hidden or 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 org.scalatest.{Matchers, FunSpec} | |
import spray.http.HttpEntity | |
import spray.http.MediaTypes._ | |
import spray.httpx.unmarshalling._ | |
import spray.routing.HttpService._ | |
import spray.testkit.ScalatestRouteTest | |
import spray.json._ | |
import spray.httpx.SprayJsonSupport._ | |
import spray.routing.directives._ | |
// All the fuss is about this... | |
case class User(name: String, no: Int) | |
// Json marshaller | |
object UnMarshalling extends DefaultJsonProtocol { | |
val jsonUser = jsonFormat2(User) | |
val textUser = Unmarshaller[User](`text/plain`) { | |
case HttpEntity.NonEmpty(contentType, data) => | |
val res = data.asString.drop(5).dropRight(1).split(',') | |
User(res(0), res(1).toInt) | |
} | |
implicit val userMarshal = Unmarshaller.oneOf(jsonUser, textUser) | |
} | |
class UnMarshalTest extends FunSpec with ScalatestRouteTest with Matchers { | |
import UnMarshalling._ | |
// Marshals response according to the Accept header media type | |
val putOrder = path("user") { | |
put { | |
// Namespace clash with ScalaTestRoutes.entity | |
MarshallingDirectives.entity(as[User]) { | |
user => | |
complete(s"no=${user.no}") | |
} | |
} | |
} | |
describe("Our route should") { | |
it("submit a json") { | |
val json = """ {"name" : "bender", "no" : 1234} """ | |
Put("/user", HttpEntity(`application/json`, json)) ~> putOrder ~> check { | |
responseAs[String] should equal("no=1234") | |
} | |
} | |
it("Submit text") { | |
Put("/user", HttpEntity(`text/plain`, """User(Zoidberg,322)""")) ~> putOrder ~> check { | |
responseAs[String] should equal("no=322") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment