期望server.route实际server.directive(akka,scala)

时间:2017-05-19 01:24:15

标签: scala akka

我是否知道如何将生成server.directive0的方法的输出转换为server.Route。我的代码如下

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpMethods, HttpResponse}
import akka.http.scaladsl.server.directives.BasicDirectives
import akka.http.scaladsl.server._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.ConfigFactory
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.directives.BasicDirectives.cancelRejection

import scala.collection.mutable.ListBuffer
import scala.concurrent.duration._



class RemoteAddressBlacklistProvider {

  //implicit def myRejectionHandler = RejectionHandler.newBuilder().handle {case MissingHeaderRejection("Remote-Address") => complete(HttpResponse(BadRequest,entity = "no remote address headers"))}.handleNotFound { complete((NotFound, "Not here!")) }.result()
  var blacklistedIPList : scala.collection.mutable.ListBuffer[String] = ListBuffer(" ")
  def addBlackListedIPAddress(ip : String)
  {
    blacklistedIPList += ip
  }
  def containsAddress(remoteAddress: String): Boolean = {if (blacklistedIPList.contains(remoteAddress)) true else false}
}

object MyRemoteAddressBlacklistProviderImpl extends RemoteAddressBlacklistProvider {
  addBlackListedIPAddress("192.168.1.1")
}

case class BlacklistedRejection(remoteAddress: String) extends Rejection

object UserAgentHeaders extends App with myDirective{

  def actorRefFactory = ActorSystem("akkaclient01")
  implicit val refFactory = actorRefFactory
  implicit val executionContext = scala.concurrent.ExecutionContext.Implicits.global
  implicit val futureTimeout : Timeout = Timeout(30.seconds)
  implicit val fm = ActorMaterializer()
  val config = ConfigFactory.load()
  val host = config.getString("http.host")
  val port = config.getInt("http.port")
  Http().bindAndHandle(route,host,port)
}

trait myDirective extends BasicDirectives  {
  val route: Route = {
    extractClientIP ({

      case ip => {
        path("checkforblacklistedaddress") {
          get {
            complete("Client's ip is " + ip.toOption.map(_.getHostAddress).getOrElse("unknown"))
          }
        }
      }


      }) ~ cancelRejection(MissingHeaderRejection("Remote-Address"))
    }
  }

问题在于

  

cancelRejection(MissingHeaderRejection( “远程地址”))

需要server.route但实际是server.directive0。我在不同的背景下曾多次遇到过这个问题。那么你能解释一下你的方法吗?

由于

1 个答案:

答案 0 :(得分:0)

省略大量隐式转换以从Route实例构造DirectiveN,您应该将函数(N arguments => Route)应用于实例。在您的情况下,例如cancelRejection(MissingHeaderRejection("Remote-Address"))(complete(StatusCodes.ExpectationFailed))。请参阅documentation