本文整理汇总了Scala中org.http4s.Response类的典型用法代码示例。如果您正苦于以下问题:Scala Response类的具体用法?Scala Response怎么用?Scala Response使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Response类的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
示例2: errors
//设置package包名称以及导入依赖的类
package kafka.console
package service
import org.http4s.dsl._
import journal.Logger
import org.http4s.{Challenge, Response}
import scalaz.concurrent.Task
object errors {
import exceptions._
import logging._
implicit def default(implicit log: Logger): ErrorHandler = {
case unexpected =>
log.warn(s"unexpected exception was thrown during the request execution: ${describe(unexpected)}")
InternalServerError()
}
def authentication: ErrorHandler = {
case authFail: AuthException =>
Task.delay { Response(Unauthorized) }
}
}
示例3: TestClient
//设置package包名称以及导入依赖的类
package com.github.hgiddens.ausms
package telstra
import JsonHelpers._
import io.circe.Json
import io.circe.syntax._
import org.http4s.{ Charset, MediaType, OAuth2BearerToken, Request, Response }
import org.http4s.client.{ Client, DisposableResponse }
import org.http4s.dsl._
import org.http4s.headers.{ Authorization, `Content-Type` }
import scalaz.Kleisli
import scalaz.concurrent.Task
private[telstra] object TestClient {
val key = "key"
val secret = "secret"
val accessToken = "g85MslKJGuDIPhOklSgNLbWFPu5g"
val messageId = "48E48E5EB8125001D6154CADFA19DA48"
private val jsonContentType = `Content-Type`(MediaType.`application/json`, Some(Charset.`UTF-8`))
private def perform(req: Request): Task[Response] =
req match {
case GET -> Root / "v1" / "oauth" / "token" =>
Ok().withBody(Json.obj("access_token" -> accessToken.asJson, "expires_in" -> "3599".asJson))
case POST -> Root / "v1" / "sms" / "messages" =>
(req.headers, req.headers) match {
case (Authorization(Authorization(OAuth2BearerToken(`accessToken`))), `Content-Type`(`jsonContentType`)) =>
Accepted().withBody(Json.obj("messageId" -> messageId.asJson))
}
case GET -> Root / "v1" / "sms" / "messages" / `messageId` =>
req.headers match {
case Authorization(Authorization(OAuth2BearerToken(`accessToken`))) =>
Ok().withBody(Json.obj(
"to" -> "0400000000".asJson,
"receivedTimestamp" -> "2015-02-05T14:10:14+11:00".asJson,
"sentTimestamp" -> "2015-02-05T14:10:12+11:00".asJson,
"status" -> "DELIVRD".asJson
))
}
}
def client: Client =
Client(Kleisli(perform _).map(new DisposableResponse(_, Task.now(()))), Task.now(()))
}
示例4: 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)
}
}
示例5: WebSocket
//设置package包名称以及导入依赖的类
package eve
import argonaut._, argonaut.Argonaut._, argonaut.ArgonautShapeless._
import java.lang.NumberFormatException
import org.http4s.{ Response, Uri }
import org.http4s.server.websocket._
import org.http4s.websocket.WebsocketBits._
import scalaz.stream.{Exchange, Process, Sink}
import scalaz.concurrent.Task
import scalaz._
import models._
import oauth._
import shared._
import eveapi._
import eveapi.oauth._
import eveapi.errors.EveApiError
import eveapi.utils.Decoders._
object WebSocket {
def apply(process: Process[Task, EveApiError \/ FleetState]): Task[Response] = {
val serverToClient: Process[Task, ServerToClient] = process.pipe(ApiStream.toClient.liftR[EveApiError]).map(_.fold(err => throw err, x => x))
val websocketProtocol: Process[Task, Text] = serverToClient.map(m => Text(m.asJson.nospaces))
val fromClient = ApiStream.fromClient.contramap[WebSocketFrame]({
case Text(t, _) => Parse.decodeEither[ClientToServer](t).fold(err => throw new IllegalArgumentException(s"Invalid json: $t"), x => x)
case x => throw new IllegalArgumentException(s"Unexpected message: ${x}")
})
WS(Exchange(websocketProtocol, fromClient))
}
}
示例6: RateLimitingMiddleware
//设置package包名称以及导入依赖的类
package com.imageintelligence.http4c.middleware
import java.time.Duration
import com.github.bucket4j._
import org.http4s.Response
import org.http4s.Service
import org.http4s.dsl._
object RateLimitingMiddleware {
def apply[A, B](tokenFn: A => B, bucketingFn: => Bucket): Middleware[A, Response, A, Response] = { service =>
val buckets = new java.util.concurrent.ConcurrentHashMap[B, Bucket]()
Service.lift[A, Response] { req =>
val token = tokenFn(req)
val bucket = Option(buckets.get(token)) match {
case None => {
val newBucket = bucketingFn
Option(buckets.putIfAbsent(token, newBucket)).getOrElse(newBucket)
}
case Some(b) => b
}
if (bucket.tryConsumeSingleToken())
service.run(req)
else
TooManyRequests()
}
}
def simpleThrottling[A, B](tokenFn: A => B, capacity: Long, period: Duration): Middleware[A, Response, A, Response] = {
val limit = Bandwidth.simple(capacity, period)
val bucket = Bucket4j.builder().addLimit(limit).build()
apply(tokenFn, bucket)
}
}