基于请求内容类型的不同路由 Spray Routing 1.2.1

7
我希望支持提交到同一URL的多种不同类型的内容,例如:application/x-www-form-urlencodedmultipart/form-dataapplication/json。我想要实现以下功能:
post {
  contentType(`application/x-www-form-urlencoded`) | 
  contentType(`multipart/form-data`) {
     // user POSTed a form
     entity(as[MyCaseClass]) { data =>
        complete { data.result }
     }
  } ~ contentType(`application/json`) {
     // user POSTed a JSON object
     entity(as[MyCaseClass]) { data =>
        complete { data.result }
     }
  }
}

我认为可以通过自定义编组和解组来实现这一点,但我只需要在我的服务中的一个或两个位置上使用它,这似乎非常简单。有人可以帮忙吗?

1个回答

6

由于Spray编组系统的深入技巧,有一种非常优雅的方法来实现这一点。 该代码(gist)说明了这一点:

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") {

    val json = """ {"name" : "bender", "no" : 1234} """

    it("submit a json") {
      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")
      }
    }
  }
}

哇,这是一个非常信息丰富的答案 - 但我正在寻找两种根据请求内容类型取消编组传入的POST数据的方法。无论请求以什么格式发送,我都将始终输出application/json - Sam in Oakland
反序列化程序的工作方式非常相似(再次使用隐式),因此您只需要以与我提供编组程序相同的方式明确提供解组即可。我会在接下来的24小时内查看它。 - David Weber
@SaminOakland 希望这个更接近你想要的 :) - David Weber
太棒了!非常感谢! - Sam in Oakland
我花了一个小时才找到答案,最终只有您的帮助才让我解决了问题,非常感谢! - Sergio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接