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

Scala BlazeBuilder类代码示例

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

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



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

示例1: Boot

//设置package包名称以及导入依赖的类
package me.davidvuong.http_api

import doobie.hikari.hikaritransactor
import org.http4s.server.{Server, ServerApp}
import org.http4s.server.blaze.BlazeBuilder
import org.http4s.server.syntax._
import org.http4s.HttpService
import org.log4s._
import doobie.hikari.imports._

import scalaz.concurrent._
import me.davidvuong.http_api.config.Config
import me.davidvuong.http_api.http.services.MessageHttpService
import me.davidvuong.http_api.repository.Repository
import me.davidvuong.http_api.services.MessageService
import me.davidvuong.http_api.utils.SqsQueueService

object Boot extends ServerApp {
  
  val httpService: HttpService = List(
    MessageHttpService(messageService).service
  ).reduce(_ orElse _)

  def server(args: List[String]): Task[Server] = {
    BlazeBuilder
      .bindHttp(config.http.port, config.http.host)
      .mountService(httpService)
      .withConnectorPoolSize(config.http.threadCount)
      .start
  }
} 
开发者ID:davidvuong,项目名称:docker-compose-bp,代码行数:32,代码来源:Boot.scala


示例2: Server

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

import eu.timepit.refined.auto._
import fs2.{Stream, Task}
import org.http4s.server.blaze.BlazeBuilder
import org.http4s.util.StreamApp

object Server extends StreamApp {
  override def stream(args: List[String]): Stream[Task, Nothing] =
    Stream.eval(Config.load).flatMap { config =>
      Storage.create2
      blazeBuilder(config).serve
    }

  def blazeBuilder(config: Config): BlazeBuilder =
    BlazeBuilder
      .bindHttp(config.http.port, config.http.host)
      .mountService(Service.root)
      .mountService(Service.api, "/api")
      .mountService(Service.assets, s"/${BuildInfo.assetsRoot}")
} 
开发者ID:fthomas,项目名称:kartograffel,代码行数:22,代码来源:Server.scala


示例3: Blaze

//设置package包名称以及导入依赖的类
package org.mdoc.rendering.service

import eu.timepit.properly.Property
import eu.timepit.properly.Property.PropertySyntax
import org.http4s.server.Server
import org.http4s.server.blaze.BlazeBuilder
import scalaz.concurrent.Task

object Blaze {
  val httpHost: Property[String] = {
    val defaultHost = "::"
    Property.getOrElse("HTTP_HOST", defaultHost)
  }

  val httpPort: Property[Int] = {
    val defaultPort = 8081
    Property.getAsIntOrElse("HTTP_PORT", defaultPort)
  }

  val serverBuilder: Property[BlazeBuilder] =
    for {
      host <- httpHost
      port <- httpPort
    } yield {
      BlazeBuilder
        .bindHttp(port, host)
        .mountService(Service.route)
    }

  val server: Task[Server] =
    serverBuilder.runTask.flatMap(_.start)
} 
开发者ID:m-doc,项目名称:rendering-service,代码行数:33,代码来源:Blaze.scala


示例4: Boot

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

import java.util.concurrent.Executors
import java.util.zip.Deflater

import com.imageintelligence.http4c.middleware.{LoggingMiddleware, MetricsMiddleware}
import com.imageintelligence.metrics.DogStatsDMetrics
import com.imageintelligence.metrics.NonBlockingDogStatsDMetrics
import com.imageintelligence.pix.api.http.services.{ImageHttpService, HealthHttpService}
import com.imageintelligence.pix.config.Config
import com.imageintelligence.pix.repository.Repository
import com.imageintelligence.pix.services._
import doobie.hikari.hikaritransactor.HikariTransactor
import org.http4s.client.blaze.PooledHttp1Client
import org.http4s.server.blaze.BlazeBuilder
import org.http4s.server.middleware.{GZip, AutoSlash}
import org.http4s.server.syntax._
import org.http4s.server._
import org.log4s.getLogger

import scalaz.concurrent.Task

object Boot extends ServerApp {
  val config = Config.loadUnsafe
  val logger = getLogger
  val metrics: DogStatsDMetrics = NonBlockingDogStatsDMetrics(
    config.metrics.prefix,
    config.metrics.host,
    config.metrics.port
  )

  
  val httpServices = List(
    ImageHttpService(imageUploadService, logger).service,
    HealthHttpService.service
  ).reduce(_ orElse _)

  val composedHttpServices = httpMiddleware(httpServices)

  def server(args: List[String]): Task[Server] = {
    BlazeBuilder
      .bindHttp(config.http.port, config.http.host)
      .mountService(composedHttpServices, "/")
      .withServiceExecutor(httpRequestExecutor)
      .withNio2(true)
      .enableHttp2(true)
      .start
  }
} 
开发者ID:ImageIntelligence,项目名称:pix-api,代码行数:50,代码来源:Boot.scala


示例5: Main

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

import java.nio.file.Paths

import com.typesafe.config.ConfigFactory
import io.grhodes.mcm.server.apn.ApnService
import io.grhodes.mcm.server.gcm.XmppBuilder
import org.http4s.server.SSLSupport.StoreInfo
import org.http4s.server.blaze.BlazeBuilder
import org.http4s.server.{Server, ServerApp}

import scalaz.concurrent.Task

object Main extends ServerApp {

  //System.setProperty("javax.net.debug", "all")
  System.setProperty("file.encoding", "UTF8")

  val ServerConfig = ConfigFactory.load().getConfig("io.grhodes.mcm-server")
  val KeyStoreConfig = ServerConfig.getConfig("apn.keystore")
  val KeyPath = Paths.get(KeyStoreConfig.getString("path")).toAbsolutePath.toString

  val ApnServer = BlazeBuilder.enableHttp2(true).withSSL(
      StoreInfo(KeyPath, KeyStoreConfig.getString("password")),
      keyManagerPassword = KeyStoreConfig.getString("manager-password"),
      trustStore = Some(StoreInfo(KeyPath, KeyStoreConfig.getString("password")))
    ).mountService(McmService.service, "/").bindHttp(ServerConfig.getInt("apn.port"))

  override def server(args: List[String]): Task[Server] = {
    XmppBuilder.start()
    ApnServer.start
  }

  override def shutdown(server: Server) = {
    XmppBuilder.shutdown()
    server.shutdown
  }

} 
开发者ID:grahamar,项目名称:mcm-server,代码行数:40,代码来源:Main.scala


示例6: ProfileEndpoint

//设置package包名称以及导入依赖的类
package pl.immutables.monads.endpoints

import io.circe.syntax._
import io.circe.generic.auto._

import org.http4s._
import org.http4s.circe._
import org.http4s.dsl._
import org.http4s.server.blaze.BlazeBuilder
import org.http4s.util.CaseInsensitiveString

import scalaz._
import scalaz.Scalaz._

import pl.immutables.monads.models._
import pl.immutables.monads.services._

import scalaz.concurrent.Task

object ProfileEndpoint extends App {
  lazy val tokenHeader = CaseInsensitiveString("token")

  lazy val service = HttpService {
    case req @ GET -> Root / "profile" => for {
      token <- req.headers.get(tokenHeader) |> 
        Result.ofOption(BadRequest("missing token"))

      user <- UserService.authenticate(token.value) |> 
        Result.ofTEither(e => Forbidden("invalid token"))

      devices <- Task.gatherUnordered(
          user.devices.map(id => DeviceService.getById(id))
        ) |> Result.ofTask
    } yield Ok(UserWithDevices(user, devices.flatten).asJson)
  }

  BlazeBuilder
    .mountService(service)
    .run.awaitShutdown()
} 
开发者ID:mbilski,项目名称:http4s-monad-transformers-example,代码行数:41,代码来源:ProfileEndpoint.scala


示例7: Bootstrap

//设置package包名称以及导入依赖的类
import api.StatusApi
import com.typesafe.scalalogging.LazyLogging
import org.http4s.server.{Server, ServerApp}
import org.http4s.server.blaze.BlazeBuilder
import utils._
import Global._
import repository.Ds._
import scalaz._, Scalaz._
import scalaz.concurrent.Task

object Bootstrap extends ServerApp with LazyLogging {

  case class ProgramStatus(s: Server, u: Unit)

  def server(args: List[String]): Task[Server] = {

    import CustomExecutor._
    import ApplicativeTask._

    val serverTask = BlazeBuilder.bindHttp(
      port = cfgVevo.getInt("http.port"),
      host = "0.0.0.0")
      .mountService(StatusApi.service, "/status").start

    T.apply2(
      Task.fork(serverTask)(ec),
      Task.fork(Task.delay(println("hellow world from Applicatives!")))(customExecutor))(ProgramStatus(_, _)
    ) map (_.s)
  }
} 
开发者ID:kayvank,项目名称:q2io-skeleton.g8,代码行数:31,代码来源:Bootstrap.scala


示例8: Demo

//设置package包名称以及导入依赖的类
package com.gvolpe.http4s.auth.demo

import com.gvolpe.http4s.auth.demo.endpoint.DemoHttpEndpoint
import com.gvolpe.http4s.auth.model.{HttpToken, HttpUser}
import com.gvolpe.http4s.auth.repository.TokenRepository
import org.http4s.server.blaze.BlazeBuilder
import org.http4s.server.{Server, ServerApp}

import scalaz.concurrent.Task
import scalaz.{\/, \/-}

object Demo extends ServerApp {

  implicit val tokenRepository = new TokenRepository {
    val fakeUser = HttpUser("gvolpe", HttpUser.createToken("gvolpe"))
    println(fakeUser.httpToken) // Just to see the generated token to use in the headers
    override def find(token: HttpToken): Task[Option[HttpUser]] = Task.now(Some(fakeUser))
    override def remove(user: HttpUser): Task[\/[Throwable, Unit]] = Task.now(\/-())
    override def save(user: HttpUser): Task[\/[Throwable, Unit]] = Task.now(\/-())
  }

  override def server(args: List[String]): Task[Server] =
    BlazeBuilder
      .bindHttp(8080, "localhost")
      //.mountService(AuthHttpEndpoint.service) IT WON'T WORK BECAUSE IT'S BASED ON Http4s v0.14.6!!!
      .mountService(DemoHttpEndpoint.service)
      .start

} 
开发者ID:gvolpe,项目名称:http4s-auth-015-demo,代码行数:30,代码来源:Demo.scala


示例9: App

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

import com.typesafe.config._
import com.typesafe.scalalogging.LazyLogging
import eventsourcing.journals.{InMemoryJournal, PollingJournalReader}
import org.http4s.server.blaze.BlazeBuilder
import project.{ProjectCommandHandler, ProjectController, ProjectEvent, ProjectQueryHandler}

object App extends LazyLogging {
  def main(args: Array[String]): Unit = {
    val port = ConfigFactory.load("server").getInt("serverInfo.port")

    val projectJournal = InMemoryJournal[ProjectEvent]
    val projectPollingReader = new PollingJournalReader(projectJournal, Globals.pollingFrequency)(Globals.executor)

    val projectService = new ProjectController(
      new ProjectCommandHandler(projectJournal),
      new ProjectQueryHandler(projectPollingReader)
    )

    projectPollingReader.listenUpdates.run.runAsync(_ => ())

    val server = BlazeBuilder.bindHttp(port)
      .mountService(ProjectController.service(projectService))
      .run

    server.awaitShutdown()
  }
} 
开发者ID:artempyanykh,项目名称:fair-share,代码行数:30,代码来源:App.scala


示例10: Main

//设置package包名称以及导入依赖的类
package rip.hansolo.http4s

import org.http4s._
import org.http4s.dsl._
import org.http4s.server._
import org.http4s.server.syntax._
import org.http4s.server.staticcontent._
import org.http4s.server.staticcontent.ResourceService._
import org.http4s.server.blaze.BlazeBuilder

import rip.hansolo.http4s.service._
import rip.hansolo.http4s.dsl.HttpServiceOps._

import scalaz._

object Main extends App {

  val staticResourceService = resourceService(Config(basePath = ""))
  val redirectToKoiService = HttpService.lift(req => SeeOther(Uri.fromString("http://koi.moe").getOrElse(Uri())))


  type Path = String
  type MountingMap = Map[Path, NonEmptyList[HttpService]]

  
  val mountingMap: MountingMap = Map(
      "/" -> NonEmptyList(TilService().forDomain("blog"), MainPageService()),
      "/info" -> NonEmptyList(TellMeService().forDomains(Seq("test", "localhost"))),
      "/hello" -> NonEmptyList(HelloWorldService()),
      "/reddit" -> NonEmptyList(
        ScalaJsAppService("Reddit Api Trickery", "rip.hansolo.script.RedditPicturesScript", useMdl = true)),
      "/r/" -> NonEmptyList(RedditStaticService())
    )

  def mapMountpointsOntoBuilder(initialBuilder: ServerBuilder, mountingMap: MountingMap): ServerBuilder = {
    // fold over all entries in the mountingmap, using the initialBuilder as a start vale
    mountingMap.foldLeft(initialBuilder)(
      (builder, entry) => {
        val (path, services) = entry
        // fold the services together, in that if the first returns HttpService.notFound, the second will be tried, and so on
        import scalaz.syntax.foldable1._
        builder.mountService(services.foldLeft1(_ || _), path)
      }
    )
  }

  // the 0.0.0.0 enables it to be picked up from outside
  val serverBuilder = mapMountpointsOntoBuilder(BlazeBuilder.bindHttp(80, "0.0.0.0"), mountingMap)

  serverBuilder
    .mountService(GithubWebhookService(), "/webhook")
    .mountService(GameService(), "/game")
    .mountService(staticResourceService, "/public")
    .mountService(redirectToKoiService, "/moe")
    .run
    .awaitShutdown()
} 
开发者ID:Giymo11,项目名称:http4s-hansolo.rip,代码行数:58,代码来源:Main.scala


示例11: ServerTests

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

import org.scalatest.FunSuite
import org.http4s.server.{Server => Http4sServer}
import org.http4s.client.blaze.SimpleHttp1Client
import org.http4s.server.blaze.BlazeBuilder

class ServerTests extends FunSuite {
  def call(path: String): String =
    SimpleHttp1Client().expect[String](s"http://localhost:8080$path").unsafePerformSync

  def withServer[A](test: Http4sServer => A): A = {
    val server: Http4sServer = BlazeBuilder.mountService(Server.service).run
    try { test(server) } finally { server.shutdownNow }
  }

  test("Static routes") {
    withServer { server =>
      val targets = Seq(
        "target/client-jsdeps.min.js",
        "target/client-opt.js",
        "target/client-launcher.js")

      assert(call("/index.html") == call("/"))
      assert(targets.forall(call("/").contains))
      assert(targets.map("/".+).map(call).forall(_.contains("typeof")))
    }
  }
} 
开发者ID:ClementMalaingre,项目名称:19x19,代码行数:30,代码来源:ServerTests.scala


示例12: Bootstrap

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

import java.io.File

import com.typesafe.config.ConfigFactory
import org.http4s.server.ServerApp
import org.http4s.server.blaze.BlazeBuilder

import scala.concurrent.ExecutionContext

object Bootstrap extends ServerApp {
  implicit val executionContext = ExecutionContext.global

  // This looks to (an optional) boot-configuration.conf first, then falls back to application.conf for any values not found
  // The idea is we can easily define an env specific config at runtime using volume mounts at $APP_CONF
  lazy val config = ConfigFactory
    .parseFile(new File(s"${sys.env.getOrElse("APP_CONF", ".")}/boot-configuration.conf"))
    .withFallback(ConfigFactory.load())

  override def server(args: List[String]) = BlazeBuilder.bindHttp(80, "0.0.0.0")
    .mountService(AggregatorService.routes(config.getString("tracking.service.host"),
      config.getString("beacon.service.host")), "/")
    .start
} 
开发者ID:markglh,项目名称:composing-microservices-with-sbt-docker,代码行数:25,代码来源:Bootstrap.scala


示例13: Bootstrap

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

import java.io.File

import com.typesafe.config.ConfigFactory
import io.getquill.{CassandraAsyncContext, SnakeCase}
import org.http4s.server.ServerApp
import org.http4s.server.blaze.BlazeBuilder

import scala.concurrent.ExecutionContext

object Bootstrap extends ServerApp with Cassandra {
  implicit val executionContext = ExecutionContext.global

  // This looks to (an optional) boot-configuration.conf first, then falls back to application.conf for any values not found
  // The idea is we can easily define an env specific config at runtime using volume mounts at $APP_CONF
  lazy val config = ConfigFactory
    .parseFile(new File(s"${sys.env.getOrElse("APP_CONF", ".")}/boot-configuration.conf"))
    .withFallback(ConfigFactory.load())

  override def server(args: List[String]) = BlazeBuilder.bindHttp(80, "0.0.0.0")
    .mountService(TrackingService.routes(new TrackingRepo[CassandraAsyncContext[SnakeCase]]()), "/")
    .start
} 
开发者ID:markglh,项目名称:composing-microservices-with-sbt-docker,代码行数:25,代码来源:Bootstrap.scala


示例14: Bootstrap

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

import java.io.File

import com.typesafe.config.ConfigFactory
import io.getquill.{CassandraAsyncContext, SnakeCase}
import org.http4s.server.ServerApp
import org.http4s.server.blaze.BlazeBuilder

import scala.concurrent.ExecutionContext

object Bootstrap extends ServerApp with Cassandra {
  implicit val executionContext = ExecutionContext.global

  // This looks to (an optional) boot-configuration.conf first, then falls back to application.conf for any values not found
  // The idea is we can easily define an env specific config at runtime using volume mounts at $APP_CONF
  lazy val config = ConfigFactory
    .parseFile(new File(s"${sys.env.getOrElse("APP_CONF", ".")}/boot-configuration.conf"))
    .withFallback(ConfigFactory.load())

  override def server(args: List[String]) = BlazeBuilder.bindHttp(80, "0.0.0.0")
    .mountService(BeaconService.routes(new BeaconRepo[CassandraAsyncContext[SnakeCase]]()), "/")
    .start
} 
开发者ID:markglh,项目名称:composing-microservices-with-sbt-docker,代码行数:25,代码来源:Bootstrap.scala


示例15: Demo2

//设置package包名称以及导入依赖的类
package com.gvolpe.http4s.auth.demo

import com.gvolpe.http4s.auth.demo.endpoint.DemoHttpEndpoint
import com.gvolpe.http4s.auth.model.{HttpToken, HttpUser}
import com.gvolpe.http4s.auth.repository.TokenRepository
import org.http4s.server.blaze.BlazeBuilder
import org.http4s.server.{Server, ServerApp}

import scalaz.{\/, \/-}
import scalaz.concurrent.Task


object Demo2 extends ServerApp {

  implicit val tokenRepository = new TokenRepository {
    val fakeUser = HttpUser("gvolpe", HttpUser.createToken("gvolpe"))
    println(fakeUser.httpToken) // Just to see the generated token to use in the headers
    override def find(token: HttpToken): Task[Option[HttpUser]] = Task.now(Some(fakeUser))
    override def remove(user: HttpUser): Task[\/[Throwable, Unit]] = Task.now(\/-())
    override def save(user: HttpUser): Task[\/[Throwable, Unit]] = Task.now(\/-())
  }

  override def server(args: List[String]): Task[Server] = {
    BlazeBuilder
      .bindHttp(8080, "localhost")
      .mountService(DemoHttpEndpoint.service)
      .start
  }

} 
开发者ID:gvolpe,项目名称:http4s-auth,代码行数:31,代码来源:Demo2.scala


示例16: ServerMain

//设置package包名称以及导入依赖的类
package science.wasabi.tini.web


import java.io.File

import org.http4s._
import org.http4s.dsl._
import org.http4s.server.{Server, ServerApp}
import org.http4s.server.blaze.BlazeBuilder
import science.wasabi.tini.Helper

import scalaz.concurrent.Task


object ServerMain extends ServerApp {

  val helloWorldService = HttpService {
    case GET -> Root / "hello" / name =>
      Ok(s"${Helper.greeting}, $name.")
  }

  val service = HttpService {
    case request @ GET -> Root / "index.html" =>
      StaticFile.fromFile(new File("./index.html"), Some(request))
        .map(Task.now) // This one is require to make the types match up
        .getOrElse(NotFound()) // In case the file doesn't exist
  }

  override def server(args: List[String]): Task[Server] = {
    println("TiniBot2.0:  http://localhost:8080/index.html")

    BlazeBuilder
      .bindHttp(8080, "localhost")
      .mountService(helloWorldService, "/api")
      .mountService(service)
      .start
  }

  Task {
    println("Press ENTER to stop Server ...")
    System.in.read()
    System.exit(0)
  }.unsafePerformAsync( f => {
    System.err.println(f)
  })

} 
开发者ID:Giymo11,项目名称:TiniBot2.0,代码行数:48,代码来源:ServerMain.scala


示例17: ShortyHttpService

//设置package包名称以及导入依赖的类
package io.regadas.shorty.service

import argonaut.Argonaut._
import io.regadas.shorty.core.{Datastore, IdGenerator, ShortyUrl}
import org.http4s.argonaut._
import org.http4s.dsl._
import org.http4s.server.blaze.BlazeBuilder
import org.http4s.{HttpService, Uri, UrlForm}
import org.log4s.getLogger

import scala.concurrent.ExecutionContext
import scalaz.concurrent.Task

trait Logging {
  protected lazy val log = getLogger
}

object ShortyHttpService extends Logging {
  implicit val shortyUrlJson    = casecodec2(ShortyUrl.apply, ShortyUrl.unapply)("id", "location")
  implicit val shortyUrlEncoder = jsonEncoderOf[Seq[ShortyUrl]]

  def service(datastore: Datastore, idGenerator: IdGenerator)(
      implicit executionContext: ExecutionContext) = HttpService {
    case GET -> Root / id =>
      Task {
        datastore.get(id)
      } flatMap {
        case Some(e) => Found(Uri.fromString(e.location).valueOr(e => throw e))
        case None    => NotFound()
      }
    case req @ POST -> Root =>
      req.decode[UrlForm] { form =>
        val shortyUrls = form.get("url").map { url =>
          ShortyUrl(idGenerator.generate(), url)
        }

        datastore.put(shortyUrls: _*)

        Ok(shortyUrls)
      } handleWith {
        case e: Exception => BadRequest(jSingleObject("error", jString(e.getMessage)))
      }
  }
}

object ShortyService {

  val host = Option(System.getenv("SHORTY_HOST")).getOrElse("0.0.0.0")
  val port = Option(System.getenv("SHORTY_PORT")).map(_.toInt).getOrElse(8080)

  def service(datastore: Datastore, idGenerator: IdGenerator)(
      implicit executionContext: ExecutionContext = ExecutionContext.global) = {
    BlazeBuilder
      .bindHttp(port, host)
      .mountService(ShortyHttpService.service(datastore, idGenerator), "/")
      .run
      .awaitShutdown()
  }
} 
开发者ID:regadas,项目名称:shorty,代码行数:60,代码来源:Shorty.scala


示例18: ExampleService

//设置package包名称以及导入依赖的类
package com.imageintelligence.http4c.examples

import java.time.Duration

import com.imageintelligence.http4c.middleware._
import org.http4s._
import org.http4s.server._
import org.http4s.server.blaze.BlazeBuilder

import scalaz._
import Scalaz._
import scalaz.concurrent.Task

object ExampleService extends ServerApp {

  val rateLimitingMiddleware: HttpMiddleware = RateLimitingMiddleware.simpleThrottling[Request, String](req =>
    req.method.name, 1, Duration.ofSeconds(10)
  )

  val compiledService = Router(
    "/health"       -> ExampleHealthService.service,
    "/users"        -> ExampleUserService.service,
    "/bytes"        -> ExampleBytesService.service,
    "/argonaut"     -> ExampleArgonautService.service,
    "/api-response" -> ExampleApiResponse.service,
    "/rate-limited" -> rateLimitingMiddleware(ExampleUserService.service)
  )

  val metricsMiddleware = MetricsMiddleware(x => println(x), (x, y, z) => println(s"${x}, ${y}, ${z}"), "example")(_)
  val jsonLoggingMiddleware = LoggingMiddleware.jsonLoggingMiddleware(x => println(x))(_)
  val basicLoggingMiddleware = LoggingMiddleware.basicLoggingMiddleware(x => println(x))(_)
  val middlewareStack = metricsMiddleware andThen jsonLoggingMiddleware andThen basicLoggingMiddleware

  val compiledServiceWithMiddleware = middlewareStack(compiledService)

  def server(args: List[String]): Task[Server] = {
    BlazeBuilder
      .bindHttp(8080, "0.0.0.0")
      .mountService(compiledServiceWithMiddleware)
      .start
  }
} 
开发者ID:ImageIntelligence,项目名称:http4c,代码行数:43,代码来源:ExampleService.scala


示例19: Main

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

import org.http4s.server.blaze.BlazeBuilder
import org.http4s.server.middleware.{CORS, GZip}
import org.http4s.server.{Server, ServerApp}

import scalaz.concurrent.Task

object Main extends ServerApp {
  case class Config(port: Int = 8080, hostname: String = "localhost")

  override def server(args: List[String]): Task[Server] = {
    val cliParser = new scopt.OptionParser[Config]("TeSSLa Simulator Server") {
      opt[Int]('p', "port")
        .optional()
        .valueName("<port>")
        .action((x, c) => c.copy(port = x))
        .text("port to bind to - defaults to 8080")

      opt[String]('h', "hostname")
        .optional()
        .valueName("<hostname>")
        .action((x, c) => c.copy(hostname = x))
        .text("hostname to bind to - defaults to localhost")

      help("help").text("prints this usage text")
    }

    val config = cliParser.parse(args, Config()).get

    BlazeBuilder
      .bindHttp(config.port, config.hostname)
      .mountService(GZip(CORS(SimulatorService.service)))
      .start
  }
} 
开发者ID:Be-ngt-oH,项目名称:TeSSLaSim,代码行数:37,代码来源:Main.scala


示例20: JamServer

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

import java.util.concurrent.{ExecutorService, Executors}

import ch.mirichan.jam.server.storage.config.LocalFileConfigResource
import ch.mirichan.jam.server.storage.filesystem.LocalFilesystem

import scala.util.Properties.envOrNone
import scalaz.concurrent.Task
import org.http4s.server.{Server, ServerApp}
import org.http4s.server.blaze.BlazeBuilder


object JamServer extends ServerApp {

  val port : Int              = envOrNone("HTTP_PORT") map (_.toInt) getOrElse 8080
  val host : String           = "0.0.0.0"
  val pool : ExecutorService  = Executors.newCachedThreadPool()

  override def server(args: List[String]): Task[Server] = {
    val config = LocalFileConfigResource(LocalFilesystem).read
    BlazeBuilder
      .bindHttp(port, host)
      .mountService(RestApi.service)
      .withServiceExecutor(pool)
      .start
  }
} 
开发者ID:mirichan,项目名称:jam,代码行数:29,代码来源:JamServer.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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