• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala HttpResponse类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中akka.http.scaladsl.model.HttpResponse的典型用法代码示例。如果您正苦于以下问题:Scala HttpResponse类的具体用法?Scala HttpResponse怎么用?Scala HttpResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了HttpResponse类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: exportReply

//设置package包名称以及导入依赖的类
package com.github.norwae.ignifera

import java.io.StringWriter

import akka.http.scaladsl.model.{ContentType, HttpEntity, HttpResponse}
import akka.util.ByteString
import io.prometheus.client.CollectorRegistry
import io.prometheus.client.exporter.common.TextFormat
import io.prometheus.client.hotspot.DefaultExports


  def exportReply: HttpResponse = {
    val writer = new StringWriter
    TextFormat.write004(writer, registry.metricFamilySamples())
    val string = writer.toString

    HttpResponse(entity = HttpEntity.Strict(HttpExport.contentType, ByteString(string)))
  }
}

object HttpExport {
  val contentType: ContentType = ContentType.parse(TextFormat.CONTENT_TYPE_004).right.get
} 
开发者ID:Norwae,项目名称:ignifera,代码行数:24,代码来源:HttpExport.scala


示例2: MonitoringEndpointsSpec

//设置package包名称以及导入依赖的类
package org.danielwojda.obfuscator.functionaltests

import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, StatusCodes}
import org.danielwojda.obfuscator.functionaltests.dsl.AkkaImplicits
import org.danielwojda.obfuscator.functionaltests.dsl.HttpEntityImplicitConverters._
import org.scalatest.concurrent.PatienceConfiguration.Timeout
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FlatSpec, GivenWhenThen, Matchers}

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.language.postfixOps

class MonitoringEndpointsSpec extends FlatSpec with Matchers with GivenWhenThen with ScalaFutures with AkkaImplicits {

  override implicit val patienceConfig = PatienceConfig(timeout = 2 seconds)
  implicit val timeout = Timeout(patienceConfig.timeout)

  "Service" should "expose the 'status' endpoint which always returns OK" in {
    When("a 'status' endpoint is called")
    val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = "http://localhost:8080/private/status"))

    Then("Http status 200 and OK body is returned")
    whenReady(responseFuture) { response =>
      response.status shouldBe StatusCodes.OK
      response.entity.asString shouldBe "OK"
    }
  }

} 
开发者ID:wojda,项目名称:obfuscate,代码行数:32,代码来源:MonitoringEndpointsSpec.scala


示例3: StatisticDataFetcher

//设置package包名称以及导入依赖的类
package com.example

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import scala.concurrent.{ExecutionContext, Future}

class StatisticDataFetcher(implicit ec: ExecutionContext, system: ActorSystem, materializer: ActorMaterializer) extends AutoMarshaller {

  val statisticsServiceUrl = {
    val config = ConfigFactory.load()
    config.getString("statisticsServiceUrl")
  }

  def getStatistics(): Future[List[StatisticData]] = {
    implicit val serialization = this.serialization
    implicit val formats = this.formats

    val responseFuture: Future[HttpResponse] =
      Http(system).singleRequest(HttpRequest(uri = statisticsServiceUrl))

    responseFuture flatMap  { response =>
      Unmarshal(response.entity).to[StatisticsResponse] map { statisticsResponse =>
        statisticsResponse.query.results.quote
      }
    }
  }
} 
开发者ID:frossi85,项目名称:financial-statistics-crawler,代码行数:32,代码来源:StatisticDataFetcher.scala


示例4: UnMarshalling

//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing

import akka.actor.ActorSystem
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.{HttpMethods, HttpRequest, HttpResponse, MessageEntity}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.{ActorMaterializer, Materializer}
import akka.util.ByteString

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import spray.json._


object UnMarshalling {

  def main(args: Array[String]) {

    implicit val sys = ActorSystem("IntroductionToAkkaHttp")
    implicit val mat:Materializer = ActorMaterializer()

    //type FromStringUnmarshaller[T] = Unmarshaller[String, T]
    val intFuture = Unmarshal("42").to[Int]
    val int = Await.result(intFuture, 1.second)
    println("int unmarshalling "+int)

    //type FromStringUnmarshaller[T] = Unmarshaller[String, T]
    val boolFuture = Unmarshal("off").to[Boolean]
    val bool = Await.result(boolFuture, 1.second)
    println("off unmarshalling "+bool)

    //type ToEntityMarshaller[T] = Marshaller[T, MessageEntity]
    val string = "Yeah"
    val entityFuture = Marshal(string).to[MessageEntity]
    val entity = Await.result(entityFuture, 1.second) // don't block in non-test code!
    println(entity)

    //type ToResponseMarshaller[T] = Marshaller[T, HttpResponse]
    val errorMsg = "Not found, pal!"
    val responseFuture = Marshal(404 -> errorMsg).to[HttpResponse]
    val response = Await.result(responseFuture, 1.second)
    println(response)


    //type FromEntityUnmarshaller[T] = Unmarshaller[HttpEntity, T]
    val jsonByteString = ByteString("""{"name":"Hello"}""")
    val httpRequest = HttpRequest(HttpMethods.POST, entity = jsonByteString)
    val jsonDataUnmarshalledFuture = Unmarshal(httpRequest).to[String]
    val jsonDataUnmarshalled = Await.result(jsonDataUnmarshalledFuture, 1.second)
    println(jsonDataUnmarshalled)

    sys.terminate()

  }

} 
开发者ID:shashankgowdal,项目名称:introduction-to-akkahttp,代码行数:58,代码来源:UnMarshalling.scala


示例5: route

//设置package包名称以及导入依赖的类
package com.ulasakdeniz.hakker

import akka.http.scaladsl.marshalling.{Marshal, ToEntityMarshaller}
import akka.http.scaladsl.model.{HttpHeader, HttpResponse, ResponseEntity, StatusCode}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import com.typesafe.config.ConfigFactory
import com.ulasakdeniz.hakker.template.Render
import de.heikoseeberger.akkahttpcirce.CirceSupport._
import io.circe.{Encoder, Json}
import io.circe.syntax._

import scala.collection.immutable
import scala.concurrent.ExecutionContext

trait Controller extends Render {

  override lazy val config = ConfigFactory.load()
  val StatusCodes          = akka.http.scaladsl.model.StatusCodes

  def route: Route

  def apply(): Route = {
    get {
      // render frontend files
      pathPrefix("js") {
        renderDir("js")
      }
    } ~ route
  }

  def send(statusCode: StatusCode): Route = complete(statusCode)

  def send[T](statusCode: StatusCode, content: T, headers: immutable.Seq[HttpHeader] = Nil)(
      implicit marshaller: ToEntityMarshaller[T],
      ec: ExecutionContext): Route = {
    val response = Marshal(content)
      .to[ResponseEntity](marshaller, ec)
      .map(entity => {
        HttpResponse(statusCode, headers = headers).withEntity(entity)
      })
    complete(response)
  }

  def sendJson[T](statusCode: StatusCode, content: T)(implicit encoder: Encoder[T],
                                                      ec: ExecutionContext): Route = {
    sendJson(statusCode, content.asJson)
  }

  def sendJson[T](content: T)(implicit encoder: Encoder[T], ec: ExecutionContext): Route = {
    sendJson(StatusCodes.OK, content)
  }

  def sendJson(statusCode: StatusCode, json: Json)(implicit ec: ExecutionContext): Route = {
    send(statusCode, Option(json.noSpaces))
  }
} 
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:58,代码来源:Controller.scala


示例6: HttpResponseUtil

//设置package包名称以及导入依赖的类
package com.ulasakdeniz.hakker.ws

import akka.http.scaladsl.model.{HttpEntity, HttpResponse}
import akka.http.scaladsl.unmarshalling.Unmarshaller
import akka.stream.scaladsl.Sink
import akka.util.ByteString

import scala.concurrent.Future
import scala.util.{Failure, Success, Try}

package object http {

  implicit final class HttpResponseUtil(responseF: Future[HttpResponse]) extends HttpClientApi {

    val entityData: Future[ByteString] =
      for {
        response <- responseF
        byteString <- {
          val source = response.entity.dataBytes
          source.runWith(Sink.head[ByteString])
        }
      } yield byteString

    def mapStrict[T](f: HttpResponse => T): Future[T] =
      for {
        response   <- responseF
        byteString <- entityData
        strictEntity = HttpEntity.Strict(response.entity.contentType, byteString)
      } yield f(response.withEntity(strictEntity))

    def entityAs[T](implicit unmarshaller: Unmarshaller[String, T]): Future[Try[T]] = {
      val result = for {
        byteString <- entityData
        t          <- unmarshaller(byteString.utf8String)
      } yield Success(t)
      result.recover {
        case t: Throwable => Failure(t)
      }
    }
  }
} 
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:42,代码来源:package.scala


示例7: RegistryClient

//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.protocol.registry

import scala.concurrent.{ ExecutionContext, Future }

import akka.actor.ActorSystem
import akka.event.slf4j.SLF4JLogging
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.headers.{ Authorization, OAuth2BearerToken }
import akka.http.scaladsl.model.{ HttpRequest, HttpResponse, RequestEntity }
import akka.stream.Materializer
import fommil.sjs.FamilyFormats._

class RegistryClient(baseUrl: String = "http://api.flowhub.io") extends SLF4JLogging {

  def register(runtime: Runtime, token: String)(implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext): Future[HttpResponse] = {
    log.debug(s"PUT $baseUrl/runtimes/${runtime.id}")
    Marshal(runtime).to[RequestEntity].flatMap { entity =>
      Http().singleRequest(HttpRequest(
        PUT,
        s"$baseUrl/runtimes/${runtime.id}",
        List(Authorization(OAuth2BearerToken(token))),
        entity))
    }
  }

  def unregister(runtimeId: String, token: String)(implicit system: ActorSystem, mat: Materializer): Future[HttpResponse] = {
    log.debug(s"DELETE $baseUrl/runtimes/$runtimeId")
    Http().singleRequest(HttpRequest(
      DELETE,
      s"$baseUrl/runtimes/$runtimeId",
      List(Authorization(OAuth2BearerToken(token)))))
  }
} 
开发者ID:ruippeixotog,项目名称:scalafbp,代码行数:37,代码来源:RegistryClient.scala


示例8: MonitoringServer

//设置package包名称以及导入依赖的类
package com.scalaio.http.monitoring

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ContentTypes._
import akka.http.scaladsl.model.{HttpEntity, HttpResponse, StatusCodes, Uri}
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.Materializer
import com.typesafe.config.Config
import com.yammer.metrics.HealthChecks
import com.yammer.metrics.core.HealthCheckRegistry
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsArray, Json}

import scala.util.{Failure, Success}
import scala.collection.convert.wrapAsScala._

object MonitoringServer {

  lazy val logger = LoggerFactory.getLogger(getClass)

  def handleHealthchecks(registry: HealthCheckRegistry): Route = {
    path("health") {
      get {
        complete {
          val checks = registry.runHealthChecks
          val payload = JsArray(checks.map {
            case (name, result) =>
              Json.obj(
                "name" -> name,
                "healthy" -> result.isHealthy,
                "message" -> result.getMessage
              )
          }.toSeq)
          val status = if (checks.values().forall(_.isHealthy)) OK else InternalServerError
          HttpResponse(entity = HttpEntity(`application/json`, Json.stringify(payload)), status = status)
        }
      }
    }
  }

  def start(serverConfig: Config, registry: HealthCheckRegistry = HealthChecks.defaultRegistry())
           (implicit system: ActorSystem, materializer: Materializer): Unit = {
    val host = serverConfig.getString("host")
    val port = serverConfig.getInt("port")
    logger.info(s"Starting monitoring server at: $host:$port")

    val routes = handleHealthchecks(registry) ~ redirect(Uri("/health"), StatusCodes.SeeOther)
    import system.dispatcher
    Http()
      .bindAndHandle(routes, host, port).onComplete {
      case Success(Http.ServerBinding(address)) =>
        logger.info(s"Monitoring server started at :$address")
      case Failure(t) =>
        logger.error("Error while trying to start monitoring server", t)
    }
  }
} 
开发者ID:fagossa,项目名称:scalaio_akka,代码行数:61,代码来源:MonitoringServer.scala


示例9: HttpClientProvider

//设置package包名称以及导入依赖的类
package org.zalando.react.nakadi.client.providers

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{SSLContext, TrustManager, X509TrustManager}

import akka.actor.ActorContext
import akka.http.scaladsl.Http.OutgoingConnection
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.settings.ClientConnectionSettings
import akka.http.scaladsl.{Http, HttpsConnectionContext}
import akka.stream.scaladsl.Flow

import scala.concurrent.Future
import scala.concurrent.duration._


class HttpClientProvider(actorContext: ActorContext,
                         server: String, port: Int,
                         isConnectionSSL: Boolean = false,
                         acceptAnyCertificate: Boolean = false,
                         connectionTimeout: FiniteDuration) {

  val http = Http(actorContext.system)

  private val settings = {
    ClientConnectionSettings
      .apply(actorContext.system)
      .withConnectingTimeout(connectionTimeout)
      .withIdleTimeout(Duration.Inf)
  }

  val connection: Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]] = {

    isConnectionSSL match {
      case true =>
        val sslContext = if (!acceptAnyCertificate) SSLContext.getDefault else {

          val permissiveTrustManager: TrustManager = new X509TrustManager() {
            override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
            override def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
            override def getAcceptedIssuers(): Array[X509Certificate] = Array.empty
          }

          val ctx = SSLContext.getInstance("TLS")
          ctx.init(Array.empty, Array(permissiveTrustManager), new SecureRandom())
          ctx
        }
        http.outgoingConnectionHttps(server, port, new HttpsConnectionContext(sslContext), settings = settings)
      case false =>
        http.outgoingConnection(server, port, settings = settings)
    }
  }

} 
开发者ID:zalando-nakadi,项目名称:reactive-nakadi,代码行数:56,代码来源:HttpClientProvider.scala


示例10: NoAuthority

//设置package包名称以及导入依赖的类
package co.horn.alkes.auth
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.directives.Credentials

import scala.concurrent.Future
import scala.util.Random


class NoAuthority extends Authority {
  lazy val anonymous = new Random(1337L)

  def ping: Future[HttpResponse] = Future.successful(HttpResponse(StatusCodes.OK))

  def channelAccess(credentials: Credentials, channel_uuid: String): Future[Option[Long]] = {
    Future.successful(Some(anonymous.nextLong))
  }

  def overlordAccess(credentials: Credentials): Future[Option[Long]] = {
    Future.successful(Some(anonymous.nextLong))
  }
} 
开发者ID:DalenWBrauner,项目名称:Alkes-Prototype,代码行数:22,代码来源:NoAuthority.scala


示例11: addAccessControlHeaders

//设置package包名称以及导入依赖的类
package com.noedominguez.class_orchestration.restapi.utils

import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Directive0, Route}
import com.typesafe.config.ConfigFactory

trait CorsSupport {
  lazy val allowedOriginHeader = {
    val config = ConfigFactory.load()
    val sAllowedOrigin = config.getString("cors.allowed-origin")
    if (sAllowedOrigin == "*")
      `Access-Control-Allow-Origin`.*
    else
      `Access-Control-Allow-Origin`(HttpOrigin(sAllowedOrigin))
  }

  private def addAccessControlHeaders: Directive0 = {
    mapResponseHeaders { headers =>
      allowedOriginHeader +:
        `Access-Control-Allow-Credentials`(true) +:
        `Access-Control-Allow-Headers`("Token", "Content-Type", "X-Requested-With") +:
        headers
    }
  }

  private def preflightRequestHandler: Route = options {
    complete(HttpResponse(200).withHeaders(
      `Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)
    )
    )
  }

  def corsHandler(r: Route) = addAccessControlHeaders {
    preflightRequestHandler ~ r
  }
} 
开发者ID:poguez,项目名称:class_orchestration_api,代码行数:40,代码来源:CorsSupport.scala


示例12: Rejection

//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.{ActorMaterializer, Materializer}


object Rejection {

  def main(args: Array[String]) {

    implicit val sys = ActorSystem("IntroductionToAkkaHttp")
    implicit val mat:Materializer = ActorMaterializer()

    implicit def myRejectionHandler = RejectionHandler.newBuilder().handle{
      case MissingCookieRejection(cookieName) =>
        complete(HttpResponse(StatusCodes.BadRequest, entity = "No cookies, no service!!!"))
    }.handleNotFound {
      complete((StatusCodes.NotFound, "Not here!"))
    }.result()

    val route =
      path("welcome"){
        get{
          complete {
            "welcome to rest service"
          }
        }
      } ~
      path("demo"){
        get{
          complete {
            "welcome to demonstration"
          }
        }
      } ~
      path("wrong"){
        reject{
          ValidationRejection("Invalid path", None)
        }
      }

    Http().bindAndHandle(route, "localhost", 8090)

  }

} 
开发者ID:shashankgowdal,项目名称:introduction-to-akkahttp,代码行数:51,代码来源:Rejection.scala


示例13: Failure

//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.ExceptionHandler
import akka.stream.{ActorMaterializer, Materializer}


object Failure {

  def main(args: Array[String]) {

    implicit val sys = ActorSystem("IntroductionToAkkaHttp")
    implicit val mat:Materializer = ActorMaterializer()

    implicit def myExceptionHandler = ExceptionHandler {
      case _: ArithmeticException =>
        complete(HttpResponse(StatusCodes.BadRequest, entity = "Bad numbers, bad result!!!"))
      case e: Throwable => {
        println(e.getMessage)
        println(e.getStackTraceString)
        complete(HttpResponse(StatusCodes.BadRequest, entity = e.getMessage))
      }
    }

    val route =
      path("welcome"){
        get{
          complete {
            "welcome to rest service"
          }
        }
      } ~
      path("demo"){
        get {
          complete {
            100/0
            "welcome to demonstration"
          }
        }
      }

    Http().bindAndHandle(route, "localhost", 8090)
  }

} 
开发者ID:shashankgowdal,项目名称:introduction-to-akkahttp,代码行数:50,代码来源:Failure.scala


示例14: corsAllowOrigins

//设置package包名称以及导入依赖的类
package com.signalswarm

import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.{HttpHeader, HttpResponse}
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Route, Directive0, MethodRejection, RejectionHandler}

trait CorsSupport {

  protected def corsAllowOrigins: List[String]

  protected def corsAllowedHeaders: List[String]

  protected def corsAllowCredentials: Boolean

  protected def optionsCorsHeaders: List[HttpHeader]

  protected def corsRejectionHandler(allowOrigin: `Access-Control-Allow-Origin`) = RejectionHandler
    .newBuilder().handle {
    case MethodRejection(supported) =>
      complete(HttpResponse().withHeaders(
        `Access-Control-Allow-Methods`(OPTIONS, supported) ::
          allowOrigin ::
          optionsCorsHeaders
      ))
  }
    .result()

  private def originToAllowOrigin(origin: Origin): Option[`Access-Control-Allow-Origin`] =
    if (corsAllowOrigins.contains("*") || corsAllowOrigins.contains(origin.value))
      origin.origins.headOption.map(`Access-Control-Allow-Origin`.apply)
    else
      None

  def cors[T]: Directive0 = mapInnerRoute { route => context =>
    ((context.request.method, context.request.header[Origin].flatMap(originToAllowOrigin)) match {
      case (OPTIONS, Some(allowOrigin)) =>
        handleRejections(corsRejectionHandler(allowOrigin)) {
          respondWithHeaders(allowOrigin,
            `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
            preflightRequestHandler ~ route
          }
        }
      case (_, Some(allowOrigin)) =>
        respondWithHeaders(allowOrigin, `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
          route ~ preflightRequestHandler
        }
      case (_, _) =>
        route
    })(context)
  }

  private def preflightRequestHandler: Route = options {
    complete(HttpResponse(200).withHeaders(
      `Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE),
      `Access-Control-Allow-Headers`(corsAllowedHeaders)
    )
    )
  }
} 
开发者ID:rmccray,项目名称:micro-service-seed,代码行数:62,代码来源:CorsSupport.scala


示例15: addAccessControlHeaders

//设置package包名称以及导入依赖的类
package utils

import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ Directive0, Route }
import com.typesafe.config.ConfigFactory

trait CorsSupport {
  lazy val allowedOriginHeader = {
    val config = ConfigFactory.load()
    val sAllowedOrigin = config.getString("cors.allowed-origin")
    if (sAllowedOrigin == "*")
      `Access-Control-Allow-Origin`.*
    else
      `Access-Control-Allow-Origin`(HttpOrigin(sAllowedOrigin))
  }

  private def addAccessControlHeaders: Directive0 = {
    mapResponseHeaders { headers =>
      allowedOriginHeader +:
        `Access-Control-Allow-Credentials`(true) +:
        `Access-Control-Allow-Headers`("Token", "Content-Type", "X-Requested-With") +:
        headers
    }
  }

  private def preflightRequestHandler: Route = options {
    complete(HttpResponse(200).withHeaders(
      `Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)
    ))
  }

  def corsHandler(r: Route) = addAccessControlHeaders {
    preflightRequestHandler ~ r
  }
} 
开发者ID:ziyasal,项目名称:Reserveon,代码行数:39,代码来源:CorsSupport.scala


示例16: UtilityServiceSlice

//设置package包名称以及导入依赖的类
package com.microworkflow.rest

import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._

class UtilityServiceSlice {

  val routes: Route = {
    path("") {
      pathEnd {
        complete("here")
      }
    } ~ path("info") {
      get {
        complete(HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, buildinfo.BuildInfo.toJson)))
      }
    }
  }
} 
开发者ID:polymorphic,项目名称:akka-http-svc.g8,代码行数:21,代码来源:UtilityServiceSlice.scala


示例17: ConnectionActor

//设置package包名称以及导入依赖的类
package com.github.pvoznenko.newPackage

import akka.actor.{Actor, Props}
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpMethods.GET
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, Uri}

import scala.concurrent.Future
import scala.io.StdIn


class ConnectionActor extends Actor {

  case object StartConnection

  case class ConnectWebsite(s: String)

  override def receive = {
    case StartConnection => {
      val requestHandler: HttpRequest => Future[HttpResponse] = {
        case HttpRequest(GET, Uri.Path("/pintpin"), _, _, _) => {

          val c = context.system.actorOf(Props[RequestHandler], "child1")

          val a = c ? OneSlash
          a map { p =>
            p
          }
        }
        case HttpRequest(GET, Uri.Path("/ping"), _, _, _) =>
          Future {
            HttpResponse(entity = "PONG!")
          }
        case HttpRequest(GET, Uri.Path("/crash"), _, _, _) =>
          sys.error("BOOM!")

      }


      val bindingFuture = Http().bindAndHandleAsync(requestHandler, "localhost", 8080)
      println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
      StdIn.readLine() // let it run until user presses return
      bindingFuture
        .flatMap(_.unbind()) // trigger unbinding from the port
        .onComplete(_ => system.shutdown()) // and shutdown when done

    }
  }
} 
开发者ID:aarashfeyzi,项目名称:AkkaStuff,代码行数:50,代码来源:ConnectionActor.scala


示例18:

//设置package包名称以及导入依赖的类
package reactive.queue.router

import java.util.concurrent.atomic.AtomicInteger

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory

trait QueueRouterSubscriber {
  implicit val system = ActorSystem.create("queue-router-test", ConfigFactory.load("test.akka.conf"))
  implicit val materlizer = ActorMaterializer()
  val log = LoggerFactory.getLogger(getClass)
  val counter = new AtomicInteger()

  val route = path("message") {
    post {
      entity(as[String]) { message =>
        log.info(s"*** queue router subscriber message count: ${counter.incrementAndGet}")
        if (message.isEmpty) complete(HttpResponse(NotFound)) else complete(HttpResponse(OK))
      }
    }
  }
  val server = Http().bindAndHandle(route, "127.0.0.1", 0)
} 
开发者ID:objektwerks,项目名称:reactive.queue.router,代码行数:30,代码来源:QueueRouterSubscriber.scala


示例19: LayerClientIntegrationSpec

//设置package包名称以及导入依赖的类
package com.jatescher.layer

import akka.actor.ActorSystem
import akka.http.scaladsl.model.{ HttpMethods, HttpRequest, HttpResponse, StatusCodes }
import akka.stream.ActorMaterializer
import com.typesafe.config.{ Config, ConfigFactory }
import org.scalatest.concurrent.{ IntegrationPatience, PatienceConfiguration, ScalaFutures }
import org.scalatest.{ Matchers, WordSpec }
import scala.concurrent.Future

class LayerClientIntegrationSpec extends WordSpec with Matchers with PatienceConfiguration with IntegrationPatience with ScalaFutures {
  val testConfig = ConfigFactory.load("test-application.conf")
  val router = new LayerRouter(testConfig)
  implicit val system = ActorSystem("LayerClientIntegrationSpecSystem")
  implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher

  class IntegrationLayerClient(router: LayerRouter, config: Config) extends LayerClient(router, config) {
    def testRequest(httpRequest: HttpRequest): Future[HttpResponse] = executeRequest(httpRequest)
  }

  "#executeRequest" should {
    "complete the request" in {
      val request = HttpRequest(HttpMethods.GET, uri = "https://layer.com")
      val client = new IntegrationLayerClient(router, testConfig)
      client.testRequest(request).futureValue.status shouldBe StatusCodes.OK
    }
  }

} 
开发者ID:jtescher,项目名称:layer-scala,代码行数:31,代码来源:LayerClientIntegrationSpec.scala


示例20: Router

//设置package包名称以及导入依赖的类
package gateway.restapi.http

import akka.event.LoggingAdapter
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route}
import akka.stream.ActorMaterializer
import scala.concurrent.ExecutionContext
import gateway.restapi.http.routes.{ClientsServiceRoute, GatewayRoute}
import gateway.restapi.utils.CorsSupport

class Router(clientsRouter: ClientsServiceRoute, gatewayRouter: GatewayRoute)
            (implicit executionContext: ExecutionContext, log: LoggingAdapter, materializer : ActorMaterializer)  extends CorsSupport {
  def BuildRoute: Route = {

    val exceptionHandler = ExceptionHandler {    // todo: response with internal exception message in DEBUG only
      case error: Throwable => {  // not a bad practice to catch Throwable here because it's the Root
        log.error(error, error.getMessage)
        extractUri { uri =>
          complete(HttpResponse(StatusCodes.BadRequest, entity = error.getMessage))
        }
      }
    }

    logRequestResult("gateway-sketch-rest-api") {
      handleExceptions(exceptionHandler) {
        pathPrefix("v1") {
          corsHandler {
            clientsRouter.route ~
              gatewayRouter.route
          }
        }
      } // Route.seal()
    }
    ////A Route can be "sealed" using Route.seal, which relies on the in-scope RejectionHandler and
    ////ExceptionHandler instances to convert rejections and exceptions into appropriate HTTP responses for the client.
  }
} 
开发者ID:kartavtcev,项目名称:gateway-sketch,代码行数:39,代码来源:Router.scala



注:本文中的akka.http.scaladsl.model.HttpResponse类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Collections类代码示例发布时间:2022-05-23
下一篇:
Scala UnitSpec类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap