spray-routing使用Case Class Extraction

通过Case Class Extraction的方式我们也可以做到将请求参数包装成对象,也就是使用了Case Class Extraction抽取器,相当方便

 

构建route

  val route2 = get{

    path("color"){
      
      parameters('red.as[Int], 'green.as[Int], 'blue.as[Int]).as(Color){ color =>
        complete(color.toString)
      }
    }

  }


这里有个优化的技巧,即route的构建过程与函数字面量的问题,

http://spray.io/documentation/1.2.3/spray-routing/advanced-topics/understanding-dsl-structure/

在编写route时注意该DSL规则就行了

还有就是IDEA是提示.as(Color)红色错误(不要理他,scala很"复杂",一些东西IDEA有时也无法探测到,例如implicit)

接着我们顺便编写检测器

  case class Color(red:Int,green:Int,blue:Int){
    require(red >=0&&green>=0&&blue>=0 && red<=255&&green<=255&&blue<=255)
  }

这里我一次性把三个参数检测了,或者请自行选择

 

 

整个源码:

import akka.actor.{Props, ActorSystem}
import akka.io.IO
import akka.util.Timeout
import spray.can.Http
import spray.util.LoggingContext
import spray.httpx.encoding.Gzip
import spray.routing._
import spray.http._
import StatusCodes._
import scala.concurrent.duration._


object ActorTest4 extends App{
  implicit val system = ActorSystem("mySystem")

  val MyService = system.actorOf(Props[MyService])

  implicit val timeout = Timeout(5.seconds)

  IO(Http) ! Http.Bind(MyService,interface = "localhost",port=8080)

}
class MyService extends HttpServiceActor {

  implicit val myRejectionHander = RejectionHandler{
    case MissingCookieRejection(cookieName) :: _ =>
      complete(BadRequest, "No cookies, no service!!!")
  }
  implicit  def myExceptionHander(implicit log:LoggingContext) = ExceptionHandler {
    case e : ArithmeticException =>
      requestUri { uri =>
        log.warning("Request to {} could not be handled normally", uri)
        complete(InternalServerError, "Bad numbers, bad result!!!")
      }
  }

  def receive = runRoute(route2)

  case class Color(red:Int,green:Int,blue:Int){
    require(red >=0&&green>=0&&blue>=0 && red<=255&&green<=255&&blue<=255)
  }

  val route2 = get{

    path("color"){

      parameters('red.as[Int], 'green.as[Int], 'blue.as[Int]).as(Color){ color =>
        complete(color.toString)
      }
    }

  }
}


 


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值