本文整理汇总了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
}
}
示例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")
}
}
}
示例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)))
}
}
示例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
}
}