当前位置: 首页>>代码示例>>Scala>>正文


Scala RouteResult类代码示例

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


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

示例1: ImperativeRequestContext

//设置package包名称以及导入依赖的类
package org.cristal.api.helper

import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.{RequestContext, Route, RouteResult, StandardRoute}
import scala.concurrent.Promise


final class ImperativeRequestContext(ctx: RequestContext, promise: Promise[RouteResult]) {
  private implicit val ec = ctx.executionContext
  def complete(obj: ToResponseMarshallable): Unit = ctx.complete(obj).onComplete(promise.complete)
  def fail(error: Throwable): Unit = ctx.fail(error).onComplete(promise.complete)
}

trait ApiHelper {

  def notImplementedResponse(msg: String = ""): StandardRoute =
    complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
      s"<h1>We plan to support this resource soon.</h1>"))

  def imperativelyComplete(inner: ImperativeRequestContext => Unit): Route = { ctx: RequestContext =>
    val p = Promise[RouteResult]()
    inner(new ImperativeRequestContext(ctx, p))
    p.future
  }

} 
开发者ID:frecano,项目名称:cristal,代码行数:29,代码来源:ApiHelper.scala

示例2: Server

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

import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route, RouteResult}
import com.typesafe.config.{Config, ConfigFactory}

import scala.util.Try

class Server(configOpt: Option[Config] = None) extends System with Logger[Server] {

  val config: Config = {
    val configName         = "hakker"
    lazy val defaultConfig = ConfigFactory.load(configName).getConfig(configName)
    configOpt
      .flatMap(cfg => {
        Try(cfg.getConfig(configName)).toOption.map(hakkerConfig =>
          hakkerConfig.withFallback(defaultConfig))
      })
      .getOrElse {
        log.warning(
          "Missing \"hakker\" field in the configuration file, " +
            "default configuration will be used.")
        defaultConfig
      }
  }

  val exceptionHandler: ExceptionHandler = ExceptionHandler {
    case ex: Exception =>
      extractUri { uri =>
        log.error(ex, "Request to {} could not be handled normally", uri)
        complete(HttpResponse(InternalServerError))
      }
  }

  def run(routeHandler: Route): Unit = {
    val defaultPort       = 8080
    val interface: String = Try(config.getString("interface")).getOrElse("localhost")
    val port: Int         = Try(config.getInt("port")).getOrElse(defaultPort)

    val routes: Route = handleExceptions(exceptionHandler)(routeHandler)
    val bindingFuture = http.bindAndHandle(RouteResult.route2HandlerFlow(routes), interface, port)

    log.info("Server online at http://{}:{}", interface, port)

    bindingFuture
      .map(binding => {
        sys.addShutdownHook(binding.unbind())
      })
      .recover { case ex: Exception => log.error("Failed to bind!") }

    sys.addShutdownHook {
      system.terminate()
      log.info("Actor System terminated")
    }
  }
} 
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:59,代码来源:Server.scala

示例3: AutowireServer

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

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{RequestContext, RouteResult}
import akka.util.ByteString
import boopickle.Default._
import java.nio.ByteBuffer
import scala.concurrent.{Future, ExecutionContext}
import model.Api

object AutowireServer extends autowire.Server[ByteBuffer, Pickler, Pickler] {
  override def read[R: Pickler](p: ByteBuffer) = Unpickle[R].fromBytes(p)
  override def write[R: Pickler](r: R) = Pickle.intoBytes(r)
  
  def dispatch(url: List[String])(implicit ec: ExecutionContext): RequestContext => Future[RouteResult] =
    entity(as[ByteString]) { entity =>
      val service = InMemService
      val body = Unpickle[Map[String, ByteBuffer]].fromBytes(entity.asByteBuffer)
      val request: Future[ByteBuffer] = AutowireServer.route[Api](service)(autowire.Core.Request(url, body))
      onSuccess(request)(buffer => complete(ByteString(buffer)))
    }
} 
开发者ID:bbarker,项目名称:mhtml-todo-full-stack,代码行数:23,代码来源:AutowireServer.scala

示例4: GameTickerModulePerRequest

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

import akka.actor.{Actor, ActorLogging, ActorRef, OneForOneStrategy, ReceiveTimeout, SupervisorStrategy}
import akka.event.LoggingReceive
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.marshalling.{ToResponseMarshallable, ToResponseMarshaller}
import akka.http.scaladsl.model.{HttpRequest, StatusCode, StatusCodes}
import akka.http.scaladsl.server.RouteResult
import spray.json.{JsonPrinter, RootJsonFormat}

import scala.concurrent.Promise

class GameTickerModulePerRequest[TConfig <: GameTickerConfig, TSharedState <: GameSharedState,
TPublicState <: GamePublicState : RootJsonFormat, TPrivateState <: GamePrivateState[TPublicState],
TCommand <: GameCommand : RootJsonFormat]
(message: GameMessage[TConfig, TSharedState, TPublicState, TPrivateState, TCommand],
settings: GameTickerModuleSettings,
request: HttpRequest, promise: Promise[RouteResult], target: ActorRef,
envelope: Envelope)
  extends Actor with ActorLogging with SprayJsonSupport with GameProtocol {

  import context._
  import StatusCodes._
  import message._
  import message.GameMessageProtocol._

  implicit val printer: JsonPrinter = settings.jsonPrinter

  setReceiveTimeout(settings.httpTimeout)
  target ! envelope

  def receive = LoggingReceive {
    case [email protected](id, gameMeta) =>
      if (gameMeta.status == GameStatus.GameNotConfigured) {
        complete(NotFound, res)
      }
      else
        complete(OK, res)
    case res: GameResponse => complete(OK, res)
    case v: Validation    => complete(BadRequest, v)
    case ReceiveTimeout   => complete(GatewayTimeout, Validation("Request timeout", GameEvents.Timeout))
  }

  def complete[T <: AnyRef](status: StatusCode, obj: T)(implicit marshaller: ToResponseMarshaller[T]) = {
    ToResponseMarshallable(obj).apply(request) onComplete {
      case scala.util.Success(response) =>
        promise.success(RouteResult.Complete(response.copy(status)))
        stop(self)
      case scala.util.Failure(e) =>
        promise.failure(e)
        stop(self)
    }
  }

  override val supervisorStrategy =
    OneForOneStrategy() {
      case e =>
        complete(InternalServerError, Validation("Could not complete request.", GameEvents.Unhandled, Some(e)))
        SupervisorStrategy.Stop
    }
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:62,代码来源:GameTickerModulePerRequest.scala


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