本文整理汇总了Scala中org.http4s.HttpService类的典型用法代码示例。如果您正苦于以下问题:Scala HttpService类的具体用法?Scala HttpService怎么用?Scala HttpService使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HttpService类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: Server
//设置package包名称以及导入依赖的类
package foobar
import foobar.page.{Contact, Index}
import org.http4s.MediaType.`text/html`
import org.http4s.dsl._
import org.http4s.headers.`Content-Type`
import org.http4s.server.ServerApp
import org.http4s.server.blaze._
import org.http4s.{HttpService, Response, StaticFile}
import scala.io.Source
import scala.util.Try
import scalatags.Text.TypedTag
import scalaz.concurrent.Task
object Server extends ServerApp {
def page(p: TypedTag[String]): Task[Response] =
Ok(p.render).withContentType(Some(`Content-Type`(`text/html`)))
val service = HttpService {
case GET -> Root => page(Index.page)
case GET -> Root / "contact" => page(Contact.page)
case req @ GET -> Root / path =>
println("file: " + Try(Source.fromFile(path).getLines().mkString))
StaticFile.fromResource(path.toString, Some(req)).fold(NotFound())(Task.now)
}
def server(args: List[String]) =
BlazeBuilder.bindHttp(8080)
.mountService(service, "/")
.start
}
开发者ID:julien-truffaut,项目名称:FooBar,代码行数:34,代码来源:Server.scala
示例2: 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
示例3: RestKeyMiddleware
//设置package包名称以及导入依赖的类
package moe.pizza.auth.webapp.rest
import org.http4s.server.HttpMiddleware
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import moe.pizza.auth.interfaces.UserDatabase
import moe.pizza.auth.webapp.SessionManager._
import moe.pizza.auth.webapp.Types.{HydratedSession, Session2, Session}
import org.http4s.{HttpService, _}
import org.http4s.server._
import org.slf4j.LoggerFactory
import pdi.jwt.{JwtAlgorithm, JwtCirce, JwtClaim}
import io.circe.generic.auto._
import scala.util.Try
import org.http4s.dsl.{Root, _}
import scalaz.concurrent.Task
class RestKeyMiddleware(apikeys: List[String]) extends HttpMiddleware {
override def apply(s: HttpService): HttpService = Service.lift { req =>
req.headers
.get(headers.Authorization)
.map(_.credentials.value.stripPrefix("Bearer "))
.filter(apikeys.contains) match {
case Some(k) =>
s(req)
case None =>
Unauthorized(
Challenge(scheme = "Bearer", realm = "Please enter a valid API key"))
}
}
}
开发者ID:NoApologies420,项目名称:Alliance-Auth,代码行数:33,代码来源:RestKeyMiddleware.scala
示例4: Service
//设置package包名称以及导入依赖的类
package kartograffel.server
import doobie.imports._
import io.circe.syntax._
import eu.timepit.refined.auto._
import kartograffel.shared.model.Graffel.Id
import kartograffel.shared.model.{Graffel, Position}
import org.http4s.{HttpService, MediaType}
import org.http4s.circe._
import org.http4s.dsl._
import org.http4s.server.staticcontent.{webjarService, WebjarService}
object Service {
val root = HttpService {
case GET -> Root =>
Ok(html.index).withType(MediaType.`text/html`)
}
val api = HttpService {
case GET -> Root / "graffel" / id =>
Ok(Graffel(Id(id), Position(0.0, 0.0)).asJson)
case req @ POST -> Root / "post" =>
val pos = req.as(jsonOf[Position])
val pos1 = pos.unsafeRun()
println(pos1)
println(Storage)
println(Storage.insertGraffel(Graffel(Id("0"), pos1)).run.transact(Storage.transactor).unsafeRun())
Ok("")
case GET -> Root / "now.json" =>
Ok(Storage.now.map(_.asJson))
case GET -> Root / "version" =>
Ok(BuildInfo.version.asJson)
}
val assets: HttpService =
webjarService(WebjarService.Config())
}
开发者ID:fthomas,项目名称:kartograffel,代码行数:41,代码来源:Service.scala
示例5: ProjectController
//设置package包名称以及导入依赖的类
package fairshare.backend.project
import java.util.UUID
import argonaut.Argonaut._
import argonaut.Json
import org.http4s.argonaut._
import org.http4s.dsl._
import org.http4s.{ HttpService, Request, Response }
import fairshare.backend.util.RequestValidation._
import fairshare.backend.util.JsonHelpers._
import scalaz.concurrent.Task
class ProjectController(commandHandler: ProjectCommandHandler, queryHandler: ProjectQueryHandler) {
def create(request: Request): Task[Response] = bindFromRequest(
request,
"name" -> nonEmptyString,
"motto" -> nonEmptyString
) { (name, motto) =>
val id = ProjectId(UUID.randomUUID())
commandHandler.create(id, name, motto).flatMap(
_.fold(
error => InternalServerError(error),
fact => Ok(Json("id" := fact.subject))
)
)
}.fold(
errs => BadRequest(errs.asJson),
success => success
)
def index(request: Request): Task[Response] = {
val projects = queryHandler.getAll
Ok(projects.asJson)
}
}
object ProjectController {
def service(controller: ProjectController): HttpService = HttpService {
case req @ GET -> Root / "index" => controller.index(req)
case req @ POST -> Root / "create" => controller.create(req)
}
}
开发者ID:artempyanykh,项目名称:fair-share,代码行数:50,代码来源:ProjectController.scala
示例6: AuthServiceSpec
//设置package包名称以及导入依赖的类
package com.example.httpservice
import com.example.model.User
import io.circe.Json
import io.circe.parser.parse
import org.http4s.{Cookie, Header, HttpService}
import org.http4s.util.CaseInsensitiveString
import org.scalatest.Matchers._
class AuthServiceSpec extends HttpTestSuite with testUserDao {
val authHttpService: HttpService = AuthHttpService(userDaoTest).service
test("log user") {
val user = User("petro1", "[email protected]", "123456")
userDaoTest.insert(user)
val setCookieHeader = obtainAuthSetCookie(user.email, user.pass)
assert(setCookieHeader.isDefined)
assert(setCookieHeader.get.contains("authcookie"))
}
test("use a logged endpoint") {
val user = User("petro2", "[email protected]", "123456")
userDaoTest.insert(user)
val setCookieHeader = obtainAuthSetCookie(user.email, user.pass)
val headerName = setCookieHeader.get.substring(0, setCookieHeader.get.indexOf("="))
val headerValue = setCookieHeader.get.substring(setCookieHeader.get.indexOf("=") + 1)
val authHeader = Header("Cookie", Cookie(headerName, headerValue).renderString)
val response = get(authHttpService, "/verifyLogged", List(authHeader))
assert(response.status.code == 200)
val body = getResponseBody(response)
assert(body == "Welcome, you are logged " + user.name)
}
def obtainAuthSetCookie(email: String, pass: String): Option[String] = {
val bodyRequest = parse("{\"email\":\"" + email + "\", \"password\":\"" + pass + "\"}").right.get
val response = post(authHttpService, "/login", bodyRequest)
assert(response.status.code == 200)
val headers = getResponseHeaders(response)
headers.get(CaseInsensitiveString("Set-Cookie")).map(_.value)
}
}
开发者ID:mpetrone,项目名称:scala-functional-rest-api,代码行数:48,代码来源:AuthServiceSpec.scala
示例7: MessageHttpService
//设置package包名称以及导入依赖的类
package me.davidvuong.http_api.http.services
import scalaz._
import org.http4s.HttpService
import org.http4s.dsl._
import com.imageintelligence.http4c.ArgonautInstances._
import com.imageintelligence.http4c.ApiResponse
import me.davidvuong.http_api.services.MessageService
import me.davidvuong.http_api.domain.http.{CreateMessageRequestDto, CreateMessageResponseDto}
case class MessageHttpService(messageService: MessageService) {
val service = HttpService {
case req @ POST -> Root / "message" => req.decode[CreateMessageRequestDto] { m =>
messageService.createMessage(m.message, m.correlationId, m.webhookUrl).flatMap {
case -\/(error) => BadRequest(ApiResponse.failure(error.toString))
case \/-(message) =>
Ok(ApiResponse.success(CreateMessageResponseDto(message.id, message.status, message.createdAt)))
}
}
}
}
开发者ID:davidvuong,项目名称:docker-compose-bp,代码行数:24,代码来源:MessageHttpService.scala
示例8: TilService
//设置package包名称以及导入依赖的类
package rip.hansolo.http4s.service
import org.http4s.HttpService
import org.http4s.MediaType._
import org.http4s.dsl._
import org.http4s.headers.`Content-Type`
object TilService {
def apply() = service
val service = HttpService.lift( req =>
Ok(<html>
<body style="margin: 0">
<iframe style="width: 100%; height: 100%; border: 0; margin: 0"
src="https://docs.google.com/document/d/1EKExnRpNokVGlOvYpKQA2COOrITBlywvgANAN9qNnEE/pub?embedded=true"></iframe>
</body>
</html>.toString()
).withContentType(Some(`Content-Type`(`text/html`)))
)
}
开发者ID:Giymo11,项目名称:http4s-hansolo.rip,代码行数:23,代码来源:TilService.scala
示例9: Routes
//设置package包名称以及导入依赖的类
package com.onur.moviedb
import com.onur.moviedb.route.{MovieRoute, AuthenticationRoute, UserRoute}
import org.http4s.HttpService
import org.http4s.server.Router
class Routes {
val privateRoutes: HttpService = Router(
"/movie" -> MovieRoute.route,
"/user" -> UserRoute.route,
"/auth" -> AuthenticationRoute.privateRoute
)
val publicRoutes: HttpService = Router(
"/auth" -> AuthenticationRoute.publicRoute
)
}
开发者ID:onurzdg,项目名称:movie-db,代码行数:19,代码来源:Routes.scala
示例10: ModernLibsService
//设置package包名称以及导入依赖的类
package org.modernlibs
import io.circe.generic.auto._
import io.circe.syntax._
import org.http4s.circe.{jsonEncoder, jsonOf}
import org.http4s.dsl._
import org.http4s.{HttpService, Request}
class ModernLibsService(db: DB) {
val modernLibsService = HttpService {
case GET -> Root / "ml" / name => getPerson(name)
case GET -> Root / "ml" => getPersons
case [email protected] -> Root / "ml" => newPerson(r)
}
private def getPersons = {
for {
dbResult <- db.list()
result <- dbResult.map(r => Ok(r.asJson)) | InternalServerError()
} yield result
}
private def getPerson(name: String) = {
for {
dbResult <- db.find(name)
result <- dbResult.map(_.fold(NotFound())(r => Ok(r.asJson))) | InternalServerError()
} yield result
}
private def newPerson(r: Request) = {
for {
person <- r.as(jsonOf[Person])
dbResponse <- db.save(person)
response <- dbResponse.map {
case 1 => Created()
case _ => Conflict()
} | InternalServerError()
} yield response
}
}
开发者ID:rogern,项目名称:modernlibs,代码行数:42,代码来源:ModernLibsService.scala
示例11: Syntax
//设置package包名称以及导入依赖的类
package com.github.hgiddens.http4s.middleware.global
import java.net.InetSocketAddress
import java.util.concurrent.ExecutorService
import org.http4s.HttpService
import org.http4s.server.{HttpMiddleware, ServerBuilder}
object Syntax {
implicit class ServerBuilderExtensions(val builder: ServerBuilder) extends AnyVal {
def globalMiddleware(middleware: HttpMiddleware): ServerBuilder =
GlobalMiddlewareServerBuilder(builder, middleware)
}
}
private[global] case class GlobalMiddlewareServerBuilder(
underlying: ServerBuilder,
middleware: HttpMiddleware
) extends ServerBuilder {
type Self = GlobalMiddlewareServerBuilder
def bindSocketAddress(socketAddress: InetSocketAddress) =
copy(underlying = underlying.bindSocketAddress(socketAddress))
def withServiceExecutor(executor: ExecutorService) =
copy(underlying = underlying.withServiceExecutor(executor))
def mountService(service: HttpService, prefix: String = "") =
copy(underlying = underlying.mountService(middleware(service), prefix))
def start =
underlying.start
}
开发者ID:hgiddens,项目名称:http4s-global-middleware,代码行数:34,代码来源:GlobalMiddleware.scala
示例12: 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
示例13: Routes
//设置package包名称以及导入依赖的类
package clerk
import java.nio.file.{Path => FilePath}
import org.http4s.dsl._
import org.http4s.HttpService
import clerk.file.{ClerkFileReader}
object Routes {
def service(filePath: FilePath, lineIndex: Vector[file.LineLocation]) = HttpService {
case GET -> Root / "lines" / IntVar(ithLine) =>
if (0 <= ithLine && ithLine < lineIndex.size) {
val clerkReader: ClerkFileReader = new ClerkFileReader(filePath)
Ok(clerkReader.getLine(lineIndex(ithLine)))
} else {
PayloadTooLarge()
}
}
}
开发者ID:asariley,项目名称:clerk,代码行数:21,代码来源:Routes.scala
示例14: UserId
//设置package包名称以及导入依赖的类
package com.imageintelligence.http4c.examples
import com.imageintelligence.http4c.DslHelpers
import com.imageintelligence.http4c.headers.`X-Proxy-Cache`
import org.http4s.ParseFailure
import org.http4s.HttpService
import org.http4s.dsl._
import scalaz._
import Scalaz._
case class UserId(value: String)
sealed trait Gender
case object Male extends Gender
case object Female extends Gender
object Gender {
def fromString(s: String): String \/ Gender = s.toLowerCase match {
case "male" => Male.right
case "female" => Female.right
case other => s"${other} is not a gender. Gender must be 'male' or 'female'".left
}
}
object ExampleUserService {
implicit val GenderQueryParamDecoder =
DslHelpers.queryParamDecoderFromEither(q => Gender.fromString(q).leftMap(x => ParseFailure.apply(x, x)))
val GenderQueryParam = DslHelpers.optionalQueryParam[Gender]("gender")
val UserIdMatcher = DslHelpers.validatingPathMatcher { x =>
if (x.length > 6) UserId(x).right
else "Bad user id".left
}
val service = HttpService {
case req @ GET -> Root / UserIdMatcher(userId) :? GenderQueryParam(gender) => {
userId match {
case \/-(id) => Ok(id.value).putHeaders(`X-Proxy-Cache`(false))
case -\/(error) => BadRequest(error)
}
}
}
}
开发者ID:ImageIntelligence,项目名称:http4c,代码行数:48,代码来源:ExampleUserService.scala
示例15: ExampleApiResponse
//设置package包名称以及导入依赖的类
package com.imageintelligence.http4c.examples
import com.imageintelligence.http4c.ApiResponse
import com.imageintelligence.http4c.ApiResponseUtils
import org.http4s.dsl._
import org.http4s.HttpService
object ExampleApiResponse {
val service = HttpService {
case req @ POST -> Root => ApiResponseUtils.decodeAs[String](req) { s =>
Ok(ApiResponse.success(s))
}
case req @ GET -> Root => {
Ok(ApiResponse.success("An Api Response"))
}
}
}
开发者ID:ImageIntelligence,项目名称:http4c,代码行数:21,代码来源:ExampleApiResponse.scala
示例16: ExampleBytesService
//设置package包名称以及导入依赖的类
package com.imageintelligence.http4c.examples
import org.http4s.HttpService
import org.http4s.dsl._
import org.http4s.headers.Authorization
import scodec.bits.ByteVector
import scalaz.stream.Process
import scala.util.Random
import scalaz._
import Scalaz._
import scalaz.concurrent.Task
object ExampleBytesService {
val service: HttpService = HttpService {
case req @ _ -> Root / IntVar(n) => {
println(req.headers.get(Authorization))
val randomBytes: Process[Task, Byte] = Process.repeatEval(
Task { (Random.nextInt(256) - 128).toByte }
)
Ok(ByteVector.apply(randomBytes.take(n).runLog.run))
}
}
}
开发者ID:ImageIntelligence,项目名称:http4c,代码行数:26,代码来源:ExampleBytesService.scala
示例17: SimulatorService
//设置package包名称以及导入依赖的类
package tesslasimulator.webService
import io.circe.{Printer, Decoder, Encoder}
import io.circe.generic.auto._
import org.http4s.HttpService
import org.http4s.circe
import org.http4s.dsl._
import tesslasimulator.simulator.Simulator
import tesslasimulator.shared.StreamJsonCodec._
import ExtendedJsonCodec._
object SimulatorService {
implicit def circeJsonDecoder[A](implicit decoder: Decoder[A]) = circe.jsonOf[A]
implicit def circeJsonEncoder[A](implicit encoder: Encoder[A]) = circe.jsonEncoderWithPrinterOf[A](Printer.spaces2)
case class SimulateRequest(scenarioSpec: String, tesslaSpec: String)
val service = HttpService {
case GET -> Root => Ok("Hello World!")
case [email protected] -> Root / "simulate" =>
req.decodeStrict[SimulateRequest] { request =>
try {
Simulator.simulate(request.scenarioSpec, request.tesslaSpec) match {
case Left(streams) => Ok(Map("streams" -> streams))
case Right(errors) => Ok(Map("errors" -> errors))
}
} catch {
case e: Exception => InternalServerError(e.getClass.getCanonicalName)
}
}
}
}
开发者ID:Be-ngt-oH,项目名称:TeSSLaSim,代码行数:35,代码来源:SimulatorService.scala
示例18: Service
//设置package包名称以及导入依赖的类
package org.example
import io.circe.syntax._
import org.http4s.HttpService
import org.http4s.circe.jsonEncoder
import org.http4s.dsl._
import org.http4s.server.staticcontent.{webjarService, WebjarService}
object Service {
val api = HttpService {
case GET -> Root / "now.json" =>
Ok(Storage.now.map(_.asJson))
case GET -> Root / "version.json" =>
Ok(BuildInfo.version.asJson)
}
val assets: HttpService =
webjarService(WebjarService.Config())
}
开发者ID:fthomas,项目名称:typelevel-webapp,代码行数:21,代码来源:Service.scala
示例19: Server
//设置package包名称以及导入依赖的类
package org.scardiecat.pingpong
import org.http4s.HttpService
import org.http4s._
import org.http4s.dsl._
import org.http4s.server.blaze.BlazeBuilder
object Server extends App with PongModule {
val healthService = HttpService {
case GET -> Root / "version" =>
Ok(meta.BuildInfo.toJson)
case GET -> Root / "health" =>
Ok()
case GET -> Root / "ready" =>
Ok()
}
val builder = BlazeBuilder.bindHttp(8080, "0.0.0.0").mountService(healthService, "/")
builder.run
pongServer.start().awaitTermination()
}
开发者ID:Scardiecat,项目名称:styx-grpc-pingpong,代码行数:23,代码来源:Server.scala
示例20: TodoService
//设置package包名称以及导入依赖的类
package com.tomwadeson.todobackend.service
import com.tomwadeson.todobackend.domain.{TodoItemPatchForm, TodoItemPostForm}
import com.tomwadeson.todobackend.persistence.TodoItemRepository
import io.circe.generic.auto._
import io.circe.{Decoder, Encoder}
import org.http4s.HttpService
import org.http4s.dsl._
class TodoService(todoItemRepository: TodoItemRepository) {
// Register circe as the JSON decoder/encoder
implicit def circeJsonDecoder[A](implicit decoder: Decoder[A]) = org.http4s.circe.jsonOf[A]
implicit def circeJsonEncoder[A](implicit encoder: Encoder[A]) = org.http4s.circe.jsonEncoderOf[A]
val service: HttpService = HttpService {
case GET -> Root / "todos" =>
Ok(todoItemRepository.getAll)
case GET -> Root / "todos" / LongVar(id) =>
todoItemRepository.getById(id).fold(NotFound())(Ok(_))
case req @ POST -> Root / "todos" =>
req.decode[TodoItemPostForm] { todoItemForm =>
Created(todoItemRepository.create(todoItemForm))
}
case DELETE -> Root / "todos" / LongVar(id) => {
val todoItem = todoItemRepository.getById(id)
todoItem.foreach(item => todoItemRepository.delete(item.id))
todoItem.fold(NotFound())(Ok(_))
}
case DELETE -> Root / "todos" => {
todoItemRepository.deleteAll
Ok()
}
case req @ PATCH -> Root / "todos" / LongVar(id) =>
req.decode[TodoItemPatchForm] { todoItemForm =>
todoItemRepository.update(id, todoItemForm).fold(NotFound())(Ok(_))
}
}
}
开发者ID:tomwadeson,项目名称:todobackend-http4s,代码行数:45,代码来源:TodoService.scala
注:本文中的org.http4s.HttpService类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论