2017-05-19 50 views
0

我可以知道如何將產生server.directive0的方法的輸出轉換爲server.Route。我的代碼如下預期server.route實際server.directive(akka,scala)

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。我在不同情況下遇到過這個問題。因此你能解釋你的方法嗎?

感謝

回答

0

省略了很多隱式轉換的構造RouteDirectiveN情況下,你應該應用功能(N arguments => Route)的實例。在你的情況下,例如cancelRejection(MissingHeaderRejection("Remote-Address"))(complete(StatusCodes.ExpectationFailed))。見documentation

相關問題