本文整理汇总了Scala中org.http4s.server.blaze.BlazeBuilder类的典型用法代码示例。如果您正苦于以下问题:Scala BlazeBuilder类的具体用法?Scala BlazeBuilder怎么用?Scala BlazeBuilder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BlazeBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
}
示例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}")
}
示例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)
}
示例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
}
}
示例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
}
}
示例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()
}
示例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)
}
}
示例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
}
示例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()
}
}
示例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()
}
示例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")))
}
}
}
示例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
}
示例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
}
示例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
}
示例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
}
}