加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 19:15:35 所属栏目:安全 来源:网络整理
导读:我想支持提交到同一网址的几种不同内容类型: 例如: application / x-www-form-urlencoded,multipart / form-data,application / json 我想做的事情如下: post { contentType(`application/x-www-form-urlencoded`) | contentType(`multipart/form-data`)
我想支持提交到同一网址的几种不同内容类型:

例如:

application / x-www-form-urlencoded,multipart / form-data,application / 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 }
     }
  }
}

我认为可能有一些方法可以使用自定义编组和解组,但我只需要在我的服务中的一两个位置,这看起来很简单.有人可以帮忙吗?

解决方法

由于喷雾编组系统具有很强的巧妙性,因此有一种非常优雅的方式可以实现这一目标.代码( 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")
      }
    }
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读