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

Scala Directive0类代码示例

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

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



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

示例1: describe

//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.directives

import akka.http.documenteddsl.documentation.RouteDocumentation
import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.directives.MethodDirectives
import org.coursera.autoschema.AutoSchema


trait MethodDDirectives {

  sealed trait MethodDDirective extends DDirective0 with Product { self =>
    def describe(w: RouteDocumentation)(implicit as: AutoSchema): RouteDocumentation = w.method(self.productPrefix)
  }

  case object GET     extends MethodDDirective { val delegate: Directive0 = MethodDirectives.get }
  case object POST    extends MethodDDirective { val delegate: Directive0 = MethodDirectives.post }
  case object PUT     extends MethodDDirective { val delegate: Directive0 = MethodDirectives.put }
  case object DELETE  extends MethodDDirective { val delegate: Directive0 = MethodDirectives.delete }
  case object HEAD    extends MethodDDirective { val delegate: Directive0 = MethodDirectives.head }
  case object OPTIONS extends MethodDDirective { val delegate: Directive0 = MethodDirectives.options }
  case object PATCH   extends MethodDDirective { val delegate: Directive0 = MethodDirectives.patch }

}

object MethodDDirectives extends MethodDDirectives 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:26,代码来源:MethodDDirectives.scala


示例2: verifySignature

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

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Directive0, Route, ValidationRejection}
import bot.line.client.SignatureVerifier
import bot.line.json.EventsJsonSupport
import bot.line.model.event.{Event, Events}

trait BaseLineBot[T] extends EventsJsonSupport {

  val channelSecret: String
  val signatureVerifier: SignatureVerifier

  def verifySignature: Directive0 =
    (headerValueByName("X-Line-Signature") & entity(as[String])).tflatMap {
      case (signature, body) if signatureVerifier.isValid(channelSecret, body, signature) => pass
      case _ => reject(ValidationRejection("Invalid signature"))
    }

  def routes: Route = {
    (path("line" / "callback") & post & verifySignature & entity(as[Events])) { entity =>
      receive(entity.events)
      complete {
        "OK"
      }
    }
  }

  def receive(events: List[Event]): T
} 
开发者ID:xoyo24,项目名称:akka-http-line-bot,代码行数:31,代码来源:BaseLineBot.scala


示例3: 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


示例4: 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


示例5: 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


示例6: addAccessControlHeaders

//设置package包名称以及导入依赖的类
package gateway.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:kartavtcev,项目名称:gateway-sketch,代码行数:40,代码来源:CorsSupport.scala


示例7: addAccessControlHeaders

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

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:sumanyu,项目名称:n-body-akka,代码行数:40,代码来源:CorsSupport.scala


示例8: authorize

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.directives

import akka.http.scaladsl.server.directives.{BasicDirectives, RouteDirectives}
import akka.http.scaladsl.server.{AuthorizationFailedRejection, Directive0}
import com.flipkart.connekt.commons.entities.AppUser
import com.flipkart.connekt.commons.factories.ServiceFactory

import scala.util.Success

trait AuthorizationDirectives {

  def authorize(user: AppUser, tags: String*): Directive0 = {

    //if api-key is set, api-user
    //else user, with transient token

    ServiceFactory.getAuthorisationService.isAuthorized(user.userId, tags: _*) match {
      case Success(authorize) if authorize =>
        BasicDirectives.pass
      case _ =>
        RouteDirectives.reject(AuthorizationFailedRejection)
    }
  }

} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:26,代码来源:AuthorizationDirectives.scala


示例9: meteredResource

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.directives

import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.directives.BasicDirectives
import com.codahale.metrics.Timer
import com.flipkart.connekt.commons.metrics.Instrumented

trait MetricsDirectives extends BasicDirectives with Instrumented {

  def meteredResource(resourceId: String): Directive0 =
    extractRequestContext.flatMap { ctx =>
      val context: Timer.Context = registry.timer(getMetricName(resourceId)).time()
      mapResponse { r =>
        context.stop()
        counter(s"$resourceId.${r.status.intValue()}").inc()
        r
      }
    }
} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:20,代码来源:MetricsDirectives.scala


示例10: addAccessControlHeaders

//设置package包名称以及导入依赖的类
package me.archdev.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:samuelmartingc,项目名称:Akka-REST-service,代码行数:40,代码来源:CorsSupport.scala


示例11: addAccessControlHeaders

//设置package包名称以及导入依赖的类
package shine.st.blog

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


trait CorsSupport {
  lazy val allowedOrigin = {
    val config = ConfigFactory.load()
    val sAllowedOrigin = config.getString("cors.allowed-origin")
    HttpOrigin(sAllowedOrigin)
  }

  //this directive adds access control headers to normal responses
  private def addAccessControlHeaders: Directive0 = {
    respondWithHeaders(
      `Access-Control-Allow-Origin`(allowedOrigin),
      `Access-Control-Allow-Credentials`(true),
      `Access-Control-Allow-Headers`("Authorization", "Content-Type", "X-Requested-With")
    )
  }

  //this handles preflight OPTIONS requests.
  private def preflightRequestHandler: Route = options {
    complete(HttpResponse(StatusCodes.OK).withHeaders(`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)))
  }

  def corsHandler(route: Route) = (encodeResponseWith(Gzip) & addAccessControlHeaders) {
    preflightRequestHandler ~ route
  }
} 
开发者ID:shine-st,项目名称:blog-akka,代码行数:37,代码来源:CorsSupport.scala


示例12: validateEntity

//设置package包名称以及导入依赖的类
package org.akka.templates.validators


import akka.http.scaladsl.server.Directives.reject
import akka.http.scaladsl.server.{Directive, Directive0}
import org.akka.templates.response.rejection.UnprocessableEntityRejection
import org.validation.scala._


trait BaseValidator {
  def validateEntity[T](entity: T)(implicit validator: Validator[T]): Directive0 = {
    Directive { (inner) =>
      val validations = org.validation.scala.validate(entity)
      if (validations.isEmpty) {
        inner(())
      } else {
        reject(UnprocessableEntityRejection(validations))
      }
    }
  }
} 
开发者ID:gabfssilva,项目名称:akka-http-microservice-templates,代码行数:22,代码来源:BaseValidator.scala


示例13: validateGreeting

//设置package包名称以及导入依赖的类
package org.akka.templates

import akka.http.scaladsl.server.Directive0
import org.akka.templates.response.Greeting
import org.validation.scala._
import org.validation.scala.matchers._


package object validators extends BaseValidator{
  implicit val validator = Validator { greeting: Greeting =>
    assure("greeting" ~> (greeting.greeting is notBlank)) {
      "greeting cannot be blank"
    } ~ assure("name" ~> (greeting.name is notBlank)) {
      "name cannot be blank"
    }
  }

  def validateGreeting(greeting: Greeting): Directive0 = validateEntity(greeting)
} 
开发者ID:gabfssilva,项目名称:akka-http-microservice-templates,代码行数:20,代码来源:package.scala


示例14: addAccessControlHeaders

//设置package包名称以及导入依赖的类
package de.thepiwo.lifelogging.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:thepiwo,项目名称:open-lifelogging,代码行数:40,代码来源:CorsSupport.scala


示例15: meter

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

import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.Directives._
import com.codahale.metrics.MetricRegistry

trait MetricDirectives {
  def meter(metricRegistry: MetricRegistry) : Directive0 = {
    extractMethod.flatMap[Unit] { httpMethod =>
      extractUri.flatMap { uri ?
        metricRegistry.meter(s"meter-Method[${httpMethod.value}]-Uri[${uri.path.toString}]").mark
        pass
      }
    }
  }

  def timer(metricRegistry: MetricRegistry) : Directive0 = {
    extractMethod.flatMap[Unit] { httpMethod =>
      extractUri.flatMap { uri ?
        val timer = metricRegistry.timer(s"timer-Method[${httpMethod.value}]-Uri[${uri.path.toString}]")
        val timerContext = timer.time()
        mapRouteResult { x ?
          timerContext.stop()
          x
        }
      }
    }
  }
} 
开发者ID:PacktPublishing,项目名称:Akka-Cookbook,代码行数:30,代码来源:MetricDirectives.scala


示例16: addAccessControlHeaders

//设置package包名称以及导入依赖的类
package com.rozilo.ussemble.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:Rozilo,项目名称:uss-gallery,代码行数:40,代码来源:CorsSupport.scala


示例17: CompositeHttpService

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

import akka.actor.ActorSystem
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.Directives._
import com.wavesplatform.settings.RestAPISettings
import scorex.api.http.swagger.SwaggerDocService

case class CompositeHttpService(system: ActorSystem, apiClasses: Set[Class[_]], routes: Seq[ApiRoute], settings: RestAPISettings) {

  val swaggerService = new SwaggerDocService(system, apiClasses, settings)

  def withCors: Directive0 = if (settings.cors)
    respondWithHeader(`Access-Control-Allow-Origin`.*) else pass

  val compositeRoute =
    withCors(routes.map(_.route).reduce(_ ~ _)) ~
    swaggerService.routes ~
    (pathEndOrSingleSlash | path("swagger")) {
      redirect("/api-docs/index.html", StatusCodes.PermanentRedirect)
    } ~
    pathPrefix("api-docs") {
      pathEndOrSingleSlash {
        redirect("/api-docs/index.html", StatusCodes.PermanentRedirect)
      } ~
      getFromResourceDirectory("swagger-ui")
    } ~ options {
      respondWithDefaultHeaders(
        `Access-Control-Allow-Credentials`(true),
        `Access-Control-Allow-Headers`("Authorization", "Content-Type", "X-Requested-With", "Timestamp", "Signature"),
        `Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE))(withCors(complete(StatusCodes.OK)))
    } ~ complete(StatusCodes.NotFound)
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:37,代码来源:CompositeHttpService.scala


示例18: addAccessControlHeaders

//设置package包名称以及导入依赖的类
package smarthouse.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:andrewobukhov,项目名称:smart-house,代码行数:37,代码来源:CorsSupport.scala


示例19: addAccessControlHeaders

//设置package包名称以及导入依赖的类
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:ciaran-,项目名称:definitely-not-gwent,代码行数:38,代码来源:CorsSupport.scala


示例20: corsAllowOrigins

//设置package包名称以及导入依赖的类
package sri.sangria.mongoserver.routes

import akka.http.scaladsl.model.HttpHeader
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers.`Access-Control-Allow-Credentials`
import akka.http.scaladsl.model.headers.`Access-Control-Allow-Methods`
import akka.http.scaladsl.model.headers.`Access-Control-Allow-Origin`
import akka.http.scaladsl.model.headers.Origin
import akka.http.scaladsl.server.Directive0
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.MethodRejection
import akka.http.scaladsl.server.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)) {
            route
          }
        }
      case (_, Some(allowOrigin)) =>
        respondWithHeaders(allowOrigin, `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
          route
        }
      case (_, _) =>
        route
    })(context)
  }
} 
开发者ID:chandu0101,项目名称:sri-sangria-example,代码行数:59,代码来源:CorsSupport.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala Iteratee类代码示例发布时间:2022-05-23
下一篇:
Scala ConfigHelper类代码示例发布时间: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