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

Scala Route类代码示例

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

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



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

示例1: Demo1

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

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.{Directive, RequestContext, Route, RouteResult}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Flow

import scala.io.StdIn


object Demo1 {

  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem("my-http")
    implicit val materializer = ActorMaterializer()
    // needed for the future flatMap/onComplete in the end
    implicit val executionContext = system.dispatcher



    val route:Route =
      path("hello"){
        get {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,"<h1>Say hello to akka-http</h1>"))
        }
      }
    val map = Flow[RequestContext].map(route)
    //???????????
    val bindingFuture = Http().bindAndHandle(route,"localhost",9898)
    println(s"Server online at http://localhost:9898/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done
  }

} 
开发者ID:liuguobing634,项目名称:akka,代码行数:41,代码来源:Demo1.scala


示例2: UsersRoute

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

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.{Directives, Route}
import core.db.users.UsersDao
import core.entities.UserInformationEntityConverters._
import restapi.http.JsonSupport
import restapi.http.routes.support.SecuredAccessSupport

import scala.concurrent.ExecutionContext
import scala.util.Try

class UsersRoute(usersDao: UsersDao)(implicit ec: ExecutionContext, ac: ApiContext)
    extends Directives with SecuredAccessSupport with JsonSupport {

  val route: Route =
    pathPrefix("users") {
      securedAccess { ctx =>
        pathEndOrSingleSlash {
          get {
            complete(usersDao.findUsers().map(toUserInformationEntity))
          }
        } ~
          path("name" / Segment) { name =>
            get {
              complete {
                val maybeUser = usersDao.findUserByName(name)
                maybeUser match {
                  case Some(user) => toUserInformationEntity(user)
                  case None       => StatusCodes.NotFound
                }
              }
            } ~
              delete {
                privateResourceAccess(ctx, name) {
                  complete {
                    Try(usersDao.deleteUser(ctx.userId))
                    StatusCodes.OK
                  }
                }
              }
          }
      }
    }

} 
开发者ID:lymr,项目名称:fun-chat,代码行数:47,代码来源:UsersRoute.scala


示例3: executor

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

import akka.actor.ActorSystem
import akka.event.LoggingAdapter
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._
import akka.stream.Materializer
import com.ferhtaydn.models.{ JsonFormats, PatientInfo, PatientResult }
import com.ferhtaydn.rater.RatePredictor
import akka.http.scaladsl.model.StatusCodes._

import scala.concurrent.ExecutionContextExecutor

trait Server extends JsonFormats {

  implicit val system: ActorSystem

  implicit def executor: ExecutionContextExecutor

  implicit val materializer: Materializer

  val logger: LoggingAdapter

  def predictor: RatePredictor

  protected val routes: Route =
    pathPrefix("cancerater") {
      get {
        pathSingleSlash {
          complete("Welcome to CanceRater")
        }
      } ~
        get {
          path("cm") {
            complete {
              predictor.confusionMatrixString.map[ToResponseMarshallable] {
                case cm ? cm
              }
            }
          }
        } ~
        post {
          path("check") {
            entity(as[PatientInfo]) { patientInfo ?
              complete {
                predictor.predict(patientInfo).map[ToResponseMarshallable] {
                  case Right(score) ? PatientResult(score)
                  case Left(error)  ? BadRequest ? error
                }
              }
            }
          }
        }
    }
} 
开发者ID:ferhtaydn,项目名称:canceRater,代码行数:57,代码来源:Server.scala


示例4: UsersProtonModule

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

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route, RouteResult}
import akka.stream.ActorMaterializer
import com.typesafe.config.Config
import com.typesafe.scalalogging.LazyLogging
import scaldi.{Injectable, Module, TypesafeConfigInjector}
import spray.json.{CompactPrinter, JsonPrinter}

import scala.concurrent.ExecutionContext

class UsersProtonModule(config: Config) extends Module {
  bind[ExecutionContext] to scala.concurrent.ExecutionContext.Implicits.global
  bind[ActorSystem] to ActorSystem("ProtonUsers", config) destroyWith (_.terminate())
  bind[JsonPrinter] to CompactPrinter
}

object UsersProtonApp extends App with Injectable with LazyLogging with SprayJsonSupport with UsersProtocol {
  ProtonConfig.parse("users-dev.conf", args).foreach(c => {
    val config = c.config
    implicit val injector = TypesafeConfigInjector(config) :: new UsersProtonModule(config)
    implicit val executionContext = inject[ExecutionContext]
    implicit val system = inject[ActorSystem]
    implicit val materializer = ActorMaterializer()
    implicit val printer = inject[JsonPrinter]

    implicit val exceptionHandler = ExceptionHandler {
      case e: Exception =>
        logger.error("HTTP unhandled exception.", e)
        var message = "HTTP unhandled exception."
        if (e != null) {
          message = e.getMessage
        }
        complete(InternalServerError -> Message(message, UsersEvents.Unhandled))
    }

    def route: Route =
      pathSingleSlash {
        get {
          complete("test")
        }
      }

    Http().bindAndHandle(route, config.getString("proton.ip"), config.getInt("proton.users.http.port"))
  })
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:52,代码来源:UsersProtonApp.scala


示例5: MainRoute

//设置package包名称以及导入依赖的类
package com.ubirch.auth.server.route

import com.ubirch.auth.util.server.RouteConstants
import com.ubirch.util.mongo.connection.MongoUtil

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route


class MainRoute(implicit mongo: MongoUtil) {

  val welcome = new WelcomeRoute {}
  val deepCheck = new DeepCheckRoute {}
  val provider = new ProviderRoute {}
  val token = new TokenRoute {}
  val logout = new LogoutRoute {}
  val register = new RegisterRoute {}
  val userInfo = new UserInfoRoute() {}

  val myRoute: Route = {

    pathPrefix(RouteConstants.apiPrefix) {
      pathPrefix(RouteConstants.serviceName) {
        pathPrefix(RouteConstants.currentVersion) {

          provider.route ~
            token.route ~
            logout.route ~
            register.route ~
            userInfo.route ~
            deepCheck.route ~
            path(RouteConstants.check) {
              welcome.route
            } ~ pathEndOrSingleSlash {
            welcome.route
          }

        }
      }
    } ~
      pathSingleSlash {
        welcome.route
      }

  }

} 
开发者ID:ubirch,项目名称:ubirch-auth-service,代码行数:48,代码来源:MainRoute.scala


示例6: TestWasatAuth

//设置package包名称以及导入依赖的类
package co.horn.alkes.auth

import akka.http.scaladsl.model.HttpMethods.{DELETE, GET, POST}
import akka.http.scaladsl.model.StatusCodes.ServerError
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import akka.http.scaladsl.server.Route

class TestWasatAuth extends AuthTest {
  val auth: Authority = new WasatAuthority(config)

  describe("Alkes is able to communicate with Wasat") {
    ignore("WasatAuthority is responding to Alkes' PING calls") {
      Get(s"$BASE_PATH/auth") ~> Route.seal(routes) ~> check {
        status should not be a[ServerError]
      }
    }
  }

  describe("WasatAuthority should allow") {
    ignore("anyone to ping") {
      canAccessRoute(OAuth2BearerToken("a"), s"$BASE_PATH/ping", GET) shouldBe true
    }

    ignore("anyone to check the database is alive") {
      canAccessRoute(OAuth2BearerToken("b"), s"$BASE_PATH/database", GET) shouldBe true
    }

    ignore("anyone to accidentally use POST") {
      canAccessRoute(OAuth2BearerToken("c"), s"$BASE_PATH", POST) shouldBe true
    }

    ignore("anyone to stumble upon the wrong route") {
      canAccessRoute(OAuth2BearerToken("d"), s"$BASE_PATH/whoops/wrong/path", GET) shouldBe true
    }
  }

  describe("DummyAuthority should NOT allow") {
    ignore("anonymous users to Get server file lists") {
      canAccessRoute(OAuth2BearerToken("j"), s"$LIST_PATH", GET) shouldBe false
    }

    ignore("anonymous users to Delete server file lists") {
      canAccessRoute(OAuth2BearerToken("k"), s"$LIST_PATH", DELETE) shouldBe false
    }
  }
} 
开发者ID:DalenWBrauner,项目名称:Alkes-Prototype,代码行数:47,代码来源:TestWasatAuth.scala


示例7: canAccessRoute

//设置package包名称以及导入依赖的类
package co.horn.alkes.auth

import akka.http.scaladsl.model.HttpMethod
import akka.http.scaladsl.model.HttpMethods.{DELETE, GET, POST, PUT}
import akka.http.scaladsl.model.StatusCodes.{Forbidden, ServerError}
import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import co.horn.alkes.config.Configuration
import co.horn.alkes.dao.DataHandler
import co.horn.alkes.dao.implementations.riak.RiakDataHandler
import co.horn.alkes.log.Logger
import co.horn.alkes.rest.Routes
import org.scalatest.{FunSpec, Matchers}
import org.scalatest.concurrent.Eventually

trait AuthTest extends FunSpec with Matchers with Eventually with ScalatestRouteTest with Routes {
  val config: Configuration = Configuration.get
  val dao: DataHandler      = new RiakDataHandler(config)
  val log: Logger           = config.log.tests

  // TODO: Define these all in just ONE spot. Need to keep DRY!
  val BASE_PATH: String  = "/" + config.app.name
  val FILE_PATH: String  = BASE_PATH + "/share/file"
  val LIST_PATH: String  = BASE_PATH + "/share/filelist"
  val META_PATH: String  = BASE_PATH + "/share/metadata"
  val THUMB_PATH: String = BASE_PATH + "/share/thumbnail"

  
  def canAccessRoute(token: OAuth2BearerToken, route: String, method: HttpMethod): Boolean = {
    method match {
      case GET =>
        Get(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case PUT =>
        Put(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case DELETE =>
        Get(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case POST =>
        Post(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case m => throw new IllegalArgumentException(s"$m is not an HttpMethod accepted by Alkes.")
    }
  }
} 
开发者ID:DalenWBrauner,项目名称:Alkes-Prototype,代码行数:56,代码来源:AuthTest.scala


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


示例9: ReservationRoute

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

import akka.http.scaladsl.server.{ Directives, Route }
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport
import handlers.OAuth2DataHandler
import http.auth.OAuth2RouteProvider
import io.circe.generic.auto._
import io.circe.syntax._
import models.{ Account, ReservationCreate }
import services.{ CachingService, ReservationService }
import akka.http.scaladsl.model.StatusCodes._

import scala.concurrent.ExecutionContext
import scalaoauth2.provider.AuthInfo

class ReservationRoute(
  override val oauth2DataHandler: OAuth2DataHandler,
  reservationService: ReservationService,
  cachingService: CachingService
)(implicit executionContext: ExecutionContext)
    extends Directives
    with OAuth2RouteProvider[Account]
    with FailFastCirceSupport {

  import reservationService._

  val route: Route = pathPrefix("reservation") {
    pathEndOrSingleSlash {
      post {
        authenticateOAuth2Async[AuthInfo[Account]]("realm", oauth2Authenticator) {
          _ =>
            entity(as[ReservationCreate]) { reservation =>
              onSuccess(makeReservation(reservation)) {
                result =>
                  {
                    if (result.success) {
                      complete(result.message)
                    } else {
                      complete(BadRequest, result.message)
                    }
                  }
              }
            }
        }
      } ~ parameters('imdbId.as[String], 'screenId.as[String]) { (imdbId, screenId) =>
        {
          authenticateOAuth2Async[AuthInfo[Account]]("realm", oauth2Authenticator) {
            _ =>
              onSuccess(getReservationDetail(imdbId, screenId)) {
                case Some(detail) => complete(detail.asJson)
                case None => complete(BadRequest)
              }

          }
        }
      }
    }
  }
} 
开发者ID:ziyasal,项目名称:Reserveon,代码行数:60,代码来源:ReservationRoute.scala


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


示例11: WebJarsSupport

//设置package包名称以及导入依赖的类
package task.airport
package util

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import org.webjars.WebJarAssetLocator

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

// See: https://github.com/ThoughtWorksInc/akka-http-webjars/blob/master/src/main/scala/com/thoughtworks/akka/http/WebJarsSupport.scala
trait WebJarsSupport {

  private val webJarAssetLocator = new WebJarAssetLocator

  val webJars: Route =
    path(Segment / Remaining) { (webJar, partialPath) =>
      Try {
        webJarAssetLocator.getFullPath(webJar, partialPath)
      } match {
        case Success(fullPath) => getFromResource(fullPath)
        case Failure(_: IllegalArgumentException) => reject
        case Failure(exception) => failWith(exception)
      }
    }

}

object WebJarsSupport extends WebJarsSupport 
开发者ID:rarrabi,项目名称:task-airport,代码行数:29,代码来源:WebJarsSupport.scala


示例12: WebhooksHttpHandler

//设置package包名称以及导入依赖的类
package im.actor.server.webhooks.http.routes

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.stream.{ ActorMaterializer, Materializer }
import akka.util.Timeout
import im.actor.server.api.http.HttpHandler
import im.actor.server.group.IntegrationTokensReadCompat

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._

final class WebhooksHttpHandler()(implicit val system: ActorSystem)
  extends HttpHandler
  with OutgoingHooks
  with IngoingHooks
  with TokenStatus {

  protected implicit val ec: ExecutionContext = system.dispatcher
  implicit val materializer: Materializer = ActorMaterializer()

  implicit val timeout: Timeout = Timeout(5.seconds)

  protected val log = Logging(system, getClass)
  protected val integrationTokensKV = new IntegrationTokensReadCompat

  override def routes: Route =
    defaultVersion {
      pathPrefix("webhooks") {
        outgoing ~ ingoing ~ status
      }
    }

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:37,代码来源:WebhooksHttpHandler.scala


示例13: AboutHttpHandler

//设置package包名称以及导入依赖的类
package im.actor.server.api.http.info

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import de.heikoseeberger.akkahttpcirce.CirceSupport
import im.actor.config.ActorConfig
import im.actor.server.api.http.HttpHandler
import im.actor.server.api.http.json.{ JsonEncoders, ServerInfo }

import scala.collection.JavaConversions._

private[http] final class AboutHttpHandler()(implicit system: ActorSystem) extends HttpHandler
  with CirceSupport
  with JsonEncoders {

  private lazy val about = getServerInfo

  def routes: Route = path("about") {
    get {
      complete(OK ? about)
    }
  }

  private def getServerInfo: ServerInfo =
    ServerInfo(
      projectName = ActorConfig.projectName,
      endpoints = ActorConfig.load().getStringList("public-endpoints").toList
    )

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:33,代码来源:AboutHttpHandler.scala


示例14: DiscussionGroupsHttpHandler

//设置package包名称以及导入依赖的类
package im.actor.server.api.http.rest.groups

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import im.actor.server.db.DbExtension
import de.heikoseeberger.akkahttpplayjson.PlayJsonSupport
import im.actor.server.api.http.HttpHandler
import im.actor.server.api.http.json.{ JsonFormatters, DiscussionGroupInfo }
import im.actor.server.persist.DiscussionGroupRepo
import im.actor.server.api.http.rest.util.SecurityManager

/**
 * Created by User on 2016/10/8.
 */
private[http] final class DiscussionGroupsHttpHandler()(implicit system: ActorSystem) extends HttpHandler with PlayJsonSupport {

  import JsonFormatters._

  private lazy val db = DbExtension(system).db
  private lazy val config = system.settings.config

  override def routes: Route =
    defaultVersion {
      pathPrefix("dangchat-discussionGroups") {
        pathEnd {
          post {
            complete("The post http request is not processed!")
          }
        } ~
          get {
            //??request?? request =>
            path(Segment) { discussionGroupId ?
              //???????ctx.uri.query.get("apiPwd")
              parameters('apiPassword) { apiPassword ?
                if (SecurityManager.checkApiPassword(apiPassword, config)) {
                  //?????Id?????
                  val optDiscussionGroup = scala.concurrent.Await.result(
                    db.run(DiscussionGroupRepo.findById(discussionGroupId)), scala.concurrent.duration.Duration.Inf
                  )
                  optDiscussionGroup match {
                    case Some(discussionGroup) ? complete(OK ? DiscussionGroupInfo(discussionGroup.id, discussionGroup.groupId))
                    case None                  ? complete(OK ? DiscussionGroupInfo("", 0))
                  }
                } else {
                  complete("Api password???")
                }
              }
            }
          } ~
          put {
            complete("The put http request is not processed!")
          } ~
          delete {
            complete("The delete http request is not processed!")
          }
      }
    }

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:62,代码来源:DiscussionGroupsHttpHandler.scala


示例15: WebServer

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

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory.load

import scala.io.StdIn
import scala.language.postfixOps
import scala.util.Try

object WebServer extends App with Routes {

  implicit val system = ActorSystem("bookstore")
  implicit val materializer = ActorMaterializer()
  implicit val executionContext = system.dispatcher

  lazy val config = load("web.conf")
  lazy val apiHost = Try(config getString "http.host") getOrElse "localhost"
  lazy val apiPort = Try(config getInt "http.port") getOrElse 9000

  val binding = Http().bindAndHandle(routes, apiHost, apiPort)

  println(s"Server online at http://$apiHost:$apiPort/\nPress RETURN to stop...")
  StdIn.readLine() // let it run until user presses return
  binding flatMap (_.unbind()) onComplete (_ => system.terminate())
} 
开发者ID:jjabuk,项目名称:bookstore,代码行数:31,代码来源:WebServer.scala


示例16: PathExampleSpec

//设置package包名称以及导入依赖的类
package io.github.jlprat.akka.http.workshop.ex1

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{ FlatSpec, Matchers }


class PathExampleSpec extends FlatSpec with ScalatestRouteTest with Matchers {

  val routeToTest = new PathExample().route

  "PathExample" should "serve `/foo` paths without slash" in {
    Get("/foo") ~> routeToTest ~> check {
      responseAs[String] shouldBe "got foo"
      status shouldBe StatusCodes.OK
    }
  }

  it should "serve `/foo/` paths with slash" in {
    Get("/foo/") ~> routeToTest ~> check {
      responseAs[String] shouldBe "got foo"
      status shouldBe StatusCodes.OK
    }
  }

  it should "serve nested routes like `/foo/bar` only without trailing slash" in {
    Get("/foo/bar") ~> routeToTest ~> check {
      responseAs[String] shouldBe "got bar"
      status shouldBe StatusCodes.OK
    }
  }

  it should "respond with `404` if route doesn't exist" in {
    Get("/notExisting") ~> Route.seal(routeToTest) ~> check {
      status shouldBe StatusCodes.NotFound
    }

    Get("/notExisting") ~> routeToTest ~> check {
      rejections shouldBe Seq.empty // when a route doesn't handle a request it returns an empty rejection list
    }
  }

  it should "serve other top level routes like `/other`" in {
    Get("/other") ~> routeToTest ~> check {
      responseAs[String] shouldBe "OK"
      status shouldBe StatusCodes.OK
    }
  }

  it should "serve other top level routes like `/other` but only if they are GET" in {
    Post("/other") ~> routeToTest ~> check {
      handled shouldBe false
    }
  }
} 
开发者ID:jlprat,项目名称:akka-http-workshop,代码行数:57,代码来源:PathExampleSpec.scala


示例17: HttpService

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

import akka.event.LoggingAdapter
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import gateway.restapi.http.routes.{ClientsServiceRoute, GatewayRoute}
import gateway.restapi.services.{ClientsService, TransactionsService, WalletsService}

import scala.concurrent.ExecutionContext

class HttpService(
                   usersService: ClientsService,
                   transactionsService: TransactionsService,
                   walletsService: WalletsService
                 ) (implicit executionContext: ExecutionContext, log: LoggingAdapter, materializer : ActorMaterializer) {

  val clientsRouter = new ClientsServiceRoute(usersService)
  val gatewayRouter = new GatewayRoute(transactionsService, walletsService)
  val router = new Router(clientsRouter, gatewayRouter)

  val routes: Route = router.BuildRoute
} 
开发者ID:kartavtcev,项目名称:gateway-sketch,代码行数:23,代码来源:HttpService.scala


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


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


示例20: Main

//设置package包名称以及导入依赖的类
package co.s4n.main

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import co.s4n.infrastructure.kafka.Consumer
import co.s4n.user.route.UsersRoute

import scala.io.StdIn

object Main {

  def main(args: Array[String]): Unit = {

    implicit val system = ActorSystem("users-rest-system")
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher

    // Define route
    val route: Route = UsersRoute.route
    //    Consumer.run()

    // Startup, and listen for requests
    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
    StdIn.readLine()

    // Shutdown
    bindingFuture
      .flatMap(_.unbind())
      .onComplete(_ => system.terminate())
  }

} 
开发者ID:bazzo03,项目名称:users-api,代码行数:35,代码来源:Main.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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