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

Scala RouteResult类代码示例

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

本文整理汇总了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;未经允许,请勿转载。


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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