=htc,doc #18496 lots of small improvements and last missing docs

This commit is contained in:
Konrad Malawski 2015-10-09 15:19:36 +02:00
parent 15897a3b48
commit bb053bea2a
57 changed files with 434 additions and 189 deletions

View file

@ -76,6 +76,7 @@ object MyImplicitExceptionHandler {
class ExceptionHandlerExamplesSpec extends RoutingSpec {
"test explicit example" in {
// tests:
Get() ~> handleExceptions(MyExplicitExceptionHandler.myExceptionHandler) {
_.complete((1 / 0).toString)
} ~> check {
@ -86,6 +87,7 @@ class ExceptionHandlerExamplesSpec extends RoutingSpec {
"test implicit example" in {
import akka.http.scaladsl.server._
import MyImplicitExceptionHandler.myExceptionHandler
// tests:
Get() ~> Route.seal(ctx => ctx.complete((1 / 0).toString)) ~> check {
responseAs[String] === "Bad numbers, bad result!!!"
}

View file

@ -30,24 +30,28 @@ class FullTestKitExampleSpec extends WordSpec with Matchers with ScalatestRouteT
"The service" should {
"return a greeting for GET requests to the root path" in {
// tests:
Get() ~> smallRoute ~> check {
responseAs[String] shouldEqual "Captain on the bridge!"
}
}
"return a 'PONG!' response for GET requests to /ping" in {
// tests:
Get("/ping") ~> smallRoute ~> check {
responseAs[String] shouldEqual "PONG!"
}
}
"leave GET requests to other paths unhandled" in {
// tests:
Get("/kermit") ~> smallRoute ~> check {
handled shouldBe false
}
}
"return a MethodNotAllowed error for PUT requests to the root path" in {
// tests:
Put() ~> Route.seal(smallRoute) ~> check {
status === StatusCodes.MethodNotAllowed
responseAs[String] shouldEqual "HTTP method not allowed, supported methods: GET"

View file

@ -66,7 +66,10 @@ class RejectionHandlerExamplesSpec extends RoutingSpec {
"test custom handler example" in {
import akka.http.scaladsl.server._
Get() ~> Route.seal(reject(MissingCookieRejection("abc"))) ~> check {
val route = Route.seal(reject(MissingCookieRejection("abc")))
// tests:
Get() ~> route ~> check {
responseAs[String] === "No cookies, no service!!!"
}
}

View file

@ -9,7 +9,7 @@ import java.io.File
import akka.event.Logging
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.model.headers.{ Server, RawHeader }
import akka.http.scaladsl.server.RouteResult.{ Complete, Rejected }
import akka.http.scaladsl.server._
import akka.stream.ActorMaterializer
@ -28,6 +28,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
complete(s"The length of the request URI is $len")
}
// tests:
Get("/abcdef") ~> route ~> check {
responseAs[String] shouldEqual "The length of the request URI is 25"
}
@ -39,11 +40,12 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
complete("It's amazing!")
}
// tests:
Get("/abcdef") ~> route ~> check {
responseAs[String] shouldEqual "It's amazing!"
}
}
"0withMaterializer" in {
"withMaterializer-0" in {
val special = ActorMaterializer(namePrefix = Some("special"))
def sample() =
@ -64,6 +66,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
}
} ~ sample() // default materializer will be used
// tests:
Get("/sample") ~> route ~> check {
responseAs[String] shouldEqual s"Materialized by ${materializer.##}!"
}
@ -71,7 +74,24 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
responseAs[String] shouldEqual s"Materialized by ${special.##}!"
}
}
"0withExecutionContext" in compileOnlySpec {
"extractMaterializer-0" in {
val route =
path("sample") {
extractMaterializer { mat =>
complete {
// explicitly use the `mat` materializer:
Source.single(s"Materialized by ${mat.##}!")
.runWith(Sink.head)(mat)
}
}
} // default materializer will be used
// tests:
Get("/sample") ~> route ~> check {
responseAs[String] shouldEqual s"Materialized by ${materializer.##}!"
}
}
"withExecutionContext-0" in compileOnlySpec {
val special = system.dispatchers.lookup("special")
def sample() =
@ -90,6 +110,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
}
} ~ sample() // default execution context will be used
// tests:
Get("/sample") ~> route ~> check {
responseAs[String] shouldEqual s"Run on ${system.dispatcher.##}!"
}
@ -97,6 +118,26 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
responseAs[String] shouldEqual s"Run on ${special.##}!"
}
}
"extractExecutionContext-0" in compileOnlySpec {
def sample() =
path("sample") {
extractExecutionContext { implicit ec =>
complete {
Future(s"Run on ${ec.##}!") // uses the `ec` ExecutionContext
}
}
}
val route =
pathPrefix("special") {
sample() // default execution context will be used
}
// tests:
Get("/sample") ~> route ~> check {
responseAs[String] shouldEqual s"Run on ${system.dispatcher.##}!"
}
}
"0withLog" in {
val special = Logging(system, "SpecialRoutes")
@ -118,6 +159,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
}
} ~ sample() // default logging adapter will be used
// tests:
Get("/sample") ~> route ~> check {
responseAs[String] shouldEqual s"Logging using ${system.log}!"
}
@ -125,7 +167,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
responseAs[String] shouldEqual s"Logging using $special!"
}
}
"0withSettings" in compileOnlySpec {
"withSettings-0" in compileOnlySpec {
val special = RoutingSettings(system).copy(fileIODispatcher = "special-io-dispatcher")
def sample() =
@ -146,6 +188,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
} ~ sample() // default file-io-dispatcher will be used to read the file
}
// tests:
Post("/special/sample") ~> route ~> check {
responseAs[String] shouldEqual s"{}"
}
@ -163,6 +206,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
complete(s"The path is $p and the query is $query")
}
// tests:
Get("/abcdef?ghi=12") ~> route ~> check {
responseAs[String] shouldEqual "The path is /abcdef and the query is ghi=12"
}
@ -173,6 +217,8 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
provideStringAndLength("test") { (value, len) =>
complete(s"Value is $value and its length is $len")
}
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "Value is test and its length is 4"
}
@ -182,10 +228,55 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
response.copy(status = StatusCodes.BadGateway)
val route = mapResponse(overwriteResultStatus)(complete("abc"))
// tests:
Get("/abcdef?ghi=12") ~> route ~> check {
status shouldEqual StatusCodes.BadGateway
}
}
"mapRouteResult" in {
// this directive is a joke, don't do that :-)
val makeEverythingOk = mapRouteResult { r =>
r match {
case Complete(response) =>
// "Everything is OK!"
Complete(response.copy(status = 200))
case _ => r
}
}
val route =
makeEverythingOk {
// will actually render as 200 OK (!)
complete(StatusCodes.Accepted)
}
// tests:
Get("/") ~> route ~> check {
status shouldEqual StatusCodes.OK
}
}
"mapRouteResultFuture" in {
val tryRecoverAddServer = mapRouteResultFuture { fr =>
fr recover {
case ex: IllegalArgumentException =>
Complete(HttpResponse(StatusCodes.InternalServerError))
} map {
case Complete(res) => Complete(res.addHeader(Server("MyServer 1.0")))
case rest => rest
}
}
val route =
tryRecoverAddServer {
complete("Hello world!")
}
// tests:
Get("/") ~> route ~> check {
status shouldEqual StatusCodes.OK
header[Server] shouldEqual Some(Server("MyServer 1.0"))
}
}
"mapResponseEntity" in {
def prefixEntity(entity: ResponseEntity): ResponseEntity = entity match {
case HttpEntity.Strict(contentType, data) =>
@ -196,6 +287,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
val prefixWithTest: Directive0 = mapResponseEntity(prefixEntity)
val route = prefixWithTest(complete("abc"))
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "testabc"
}
@ -212,6 +304,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/") ~> RawHeader("id", "12345") ~> RawHeader("id2", "67890") ~> route ~> check {
header("id") shouldEqual None
header("id2").get.value shouldEqual "67890"
@ -233,6 +326,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
complete(throw new IllegalArgumentException("BLIP! BLOP! Everything broke"))
}
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "Got IllegalArgumentException 'BLIP! BLOP! Everything broke'"
}
@ -245,6 +339,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
path("abc")(complete("abc"))
}
// tests:
Get("/") ~> route ~> check {
rejection shouldEqual AuthorizationFailedRejection
}
@ -281,6 +376,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/auth/never") ~> route ~> check {
status shouldEqual StatusCodes.OK
responseAs[String] shouldEqual "Nothing to see here, move along."
@ -317,6 +413,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/auth/never") ~> route ~> check {
status shouldEqual StatusCodes.OK
responseAs[String] shouldEqual "Nothing to see here, move along."
@ -346,6 +443,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/abc/def/ghi") ~> route ~> check {
responseAs[String] shouldEqual "POST"
}
@ -360,6 +458,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
complete("abc")
}
// tests:
Get("/") ~> route ~> check {
rejections.nonEmpty shouldEqual true
}
@ -375,12 +474,51 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
reject(MyCustomRejection)
}
// tests:
Get("/") ~> route ~> check {
rejection shouldEqual AuthorizationFailedRejection
}
}
"mapRouteResultWithPF-0" in {
case object MyCustomRejection extends Rejection
val rejectRejections = // not particularly useful directive
mapRouteResultWithPF {
case Rejected(_) => Future(Rejected(List(AuthorizationFailedRejection)))
}
val route =
rejectRejections {
reject(MyCustomRejection)
}
// tests:
Get("/") ~> route ~> check {
rejection shouldEqual AuthorizationFailedRejection
}
}
"mapRouteResultWith-0" in {
case object MyCustomRejection extends Rejection
val rejectRejections = // not particularly useful directive
mapRouteResultWith { res =>
res match {
case Rejected(_) => Future(Rejected(List(AuthorizationFailedRejection)))
case _ => Future(res)
}
}
val route =
rejectRejections {
reject(MyCustomRejection)
}
// tests:
Get("/") ~> route ~> check {
rejection shouldEqual AuthorizationFailedRejection
}
}
"pass" in {
Get("/") ~> pass(complete("abc")) ~> check {
val route = pass(complete("abc"))
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "abc"
}
}
@ -390,6 +528,8 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
providePrefixedString("test") { value =>
complete(value)
}
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "prefix:test"
}
@ -407,6 +547,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/") ~> route ~> check {
rejections shouldEqual Nil
handled shouldEqual false
@ -420,6 +561,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/") ~> route ~> check {
rejections shouldEqual Nil
handled shouldEqual false
@ -431,6 +573,51 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
complete(s"Request method is ${request.method.name} and content-type is ${request.entity.contentType}")
}
// tests:
Post("/", "text") ~> route ~> check {
responseAs[String] shouldEqual "Request method is POST and content-type is text/plain; charset=UTF-8"
}
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "Request method is GET and content-type is none/none"
}
}
"extractSettings-examples" in {
val route =
extractSettings { settings: RoutingSettings =>
complete(s"RoutingSettings.renderVanityFooter = ${settings.renderVanityFooter}")
}
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual s"RoutingSettings.renderVanityFooter = true"
}
}
"mapSettings-examples" in {
val tunedSettings = mapSettings { settings =>
settings.copy(fileGetConditional = false)
}
val route =
tunedSettings {
extractSettings { settings: RoutingSettings =>
complete(s"RoutingSettings.fileGetConditional = ${settings.fileGetConditional}")
}
}
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual s"RoutingSettings.fileGetConditional = false"
}
}
"extractRequestContext-example" in {
val route =
extractRequestContext { ctx =>
ctx.log.debug("Using access to additional context availablethings, like the logger.")
val request = ctx.request
complete(s"Request method is ${request.method.name} and content-type is ${request.entity.contentType}")
}
// tests:
Post("/", "text") ~> route ~> check {
responseAs[String] shouldEqual "Request method is POST and content-type is text/plain; charset=UTF-8"
}
@ -444,6 +631,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
complete(s"Full URI: $uri")
}
// tests:
Get("/") ~> route ~> check {
// tests are executed with the host assumed to be "example.com"
responseAs[String] shouldEqual "Full URI: http://example.com/"
@ -471,6 +659,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/123/abc") ~> route ~> check {
responseAs[String] shouldEqual "Content"
}
@ -486,6 +675,7 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/abc") ~> route ~> check {
responseAs[String] shouldEqual "Unmatched: ''"
}

View file

@ -17,6 +17,7 @@ class CodingDirectivesExamplesSpec extends RoutingSpec {
"encodeResponse" in {
val route = encodeResponse { complete("content") }
// tests:
Get("/") ~> route ~> check {
response should haveContentEncoding(identity)
}
@ -33,6 +34,7 @@ class CodingDirectivesExamplesSpec extends RoutingSpec {
"encodeResponseWith" in {
val route = encodeResponseWith(Gzip) { complete("content") }
// tests:
Get("/") ~> route ~> check {
response should haveContentEncoding(gzip)
}
@ -60,6 +62,7 @@ class CodingDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Post("/", helloGzipped) ~> `Content-Encoding`(gzip) ~> route ~> check {
responseAs[String] shouldEqual "Request content: 'Hello'"
}
@ -78,6 +81,7 @@ class CodingDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Post("/", helloGzipped) ~> `Content-Encoding`(gzip) ~> route ~> check {
responseAs[String] shouldEqual "Request content: 'Hello'"
}
@ -96,6 +100,7 @@ class CodingDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Post("/", helloGzipped) ~> `Content-Encoding`(gzip) ~> route ~> check {
responseAs[String] shouldEqual "Request content: 'Hello'"
}

View file

@ -16,6 +16,7 @@ class CookieDirectivesExamplesSpec extends RoutingSpec {
complete(s"The logged in user is '${nameCookie.value}'")
}
// tests:
Get("/") ~> Cookie("userName" -> "paul") ~> route ~> check {
responseAs[String] shouldEqual "The logged in user is 'paul'"
}
@ -34,6 +35,7 @@ class CookieDirectivesExamplesSpec extends RoutingSpec {
case None => complete("No user logged in")
}
// tests:
Get("/") ~> Cookie("userName" -> "paul") ~> route ~> check {
responseAs[String] shouldEqual "The logged in user is 'paul'"
}
@ -47,6 +49,7 @@ class CookieDirectivesExamplesSpec extends RoutingSpec {
complete("The user was logged out")
}
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "The user was logged out"
header[`Set-Cookie`] shouldEqual Some(`Set-Cookie`(HttpCookie("userName", value = "deleted", expires = Some(DateTime.MinValue))))
@ -58,6 +61,7 @@ class CookieDirectivesExamplesSpec extends RoutingSpec {
complete("The user was logged in")
}
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "The user was logged in"
header[`Set-Cookie`] shouldEqual Some(`Set-Cookie`(HttpCookie("userName", value = "paul")))

View file

@ -5,11 +5,9 @@
package docs.http.scaladsl.server
package directives
import akka.http.scaladsl.model.{ HttpResponse, HttpRequest }
import akka.http.scaladsl.server._
import akka.event.Logging
import akka.http.scaladsl.server.directives.{ LoggingMagnet, LogEntry, DebuggingDirectives }
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.server.directives.{DebuggingDirectives, LogEntry, LoggingMagnet}
class DebuggingDirectivesExamplesSpec extends RoutingSpec {
"logRequest-0" in {
@ -34,6 +32,7 @@ class DebuggingDirectivesExamplesSpec extends RoutingSpec {
def printRequestMethod(req: HttpRequest): Unit = println(req.method)
val logRequestPrintln = DebuggingDirectives.logRequest(LoggingMagnet(_ => printRequestMethod))
// tests:
Get("/") ~> logRequestPrintln(complete("logged")) ~> check {
responseAs[String] shouldEqual "logged"
}
@ -60,6 +59,7 @@ class DebuggingDirectivesExamplesSpec extends RoutingSpec {
println(requestMethodAndResponseStatusAsInfo(req)(res).map(_.obj.toString).getOrElse(""))
val logRequestResultPrintln = DebuggingDirectives.logRequestResult(LoggingMagnet(_ => printRequestMethodAndResponseStatus))
// tests:
Get("/") ~> logRequestResultPrintln(complete("logged")) ~> check {
responseAs[String] shouldEqual "logged"
}
@ -89,6 +89,7 @@ class DebuggingDirectivesExamplesSpec extends RoutingSpec {
def printResponseStatus(res: Any): Unit = println(responseStatus(res))
val logResultPrintln = DebuggingDirectives.logResult(LoggingMagnet(_ => printResponseStatus))
// tests:
Get("/") ~> logResultPrintln(complete("logged")) ~> check {
responseAs[String] shouldEqual "logged"
}

View file

@ -20,6 +20,7 @@ class ExecutionDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/divide/10/5") ~> route ~> check {
responseAs[String] shouldEqual "The result is 2"
}
@ -39,6 +40,7 @@ class ExecutionDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/handled/existing") ~> route ~> check {
responseAs[String] shouldEqual "This path exists"
}

View file

@ -20,6 +20,7 @@ class FileAndResourceDirectivesExamplesSpec extends RoutingSpec {
getFromFile(".log") // uses implicit ContentTypeResolver
}
// tests:
Get("/logs/example") ~> route ~> check {
responseAs[String] shouldEqual "example file contents"
}
@ -33,6 +34,7 @@ class FileAndResourceDirectivesExamplesSpec extends RoutingSpec {
getFromResource(".log") // uses implicit ContentTypeResolver
}
// tests:
Get("/logs/example") ~> route ~> check {
responseAs[String] shouldEqual "example file contents"
}
@ -49,6 +51,7 @@ class FileAndResourceDirectivesExamplesSpec extends RoutingSpec {
listDirectoryContents("/tmp")(renderer)
}
// tests:
Get("/logs/example") ~> route ~> check {
responseAs[String] shouldEqual "example file contents"
}
@ -59,6 +62,7 @@ class FileAndResourceDirectivesExamplesSpec extends RoutingSpec {
getFromBrowseableDirectory("/tmp")
}
// tests:
Get("/tmp") ~> route ~> check {
status shouldEqual StatusCodes.OK
}
@ -69,6 +73,7 @@ class FileAndResourceDirectivesExamplesSpec extends RoutingSpec {
getFromBrowseableDirectories("/main", "/backups")
}
// tests:
Get("/tmp") ~> route ~> check {
status shouldEqual StatusCodes.OK
}
@ -79,6 +84,7 @@ class FileAndResourceDirectivesExamplesSpec extends RoutingSpec {
getFromDirectory("/tmp")
}
// tests:
Get("/tmp/example") ~> route ~> check {
responseAs[String] shouldEqual "example file contents"
}
@ -89,6 +95,7 @@ class FileAndResourceDirectivesExamplesSpec extends RoutingSpec {
getFromResourceDirectory("/examples")
}
// tests:
Get("/examples/example-1") ~> route ~> check {
responseAs[String] shouldEqual "example file contents"
}

View file

@ -15,6 +15,7 @@ class FormFieldDirectivesExamplesSpec extends RoutingSpec {
complete(s"The color is '$color' and the age ten years ago was ${age - 10}")
}
// tests:
Post("/", FormData("color" -> "blue", "age" -> "68")) ~> route ~> check {
responseAs[String] shouldEqual "The color is 'blue' and the age ten years ago was 58"
}
@ -33,6 +34,7 @@ class FormFieldDirectivesExamplesSpec extends RoutingSpec {
complete(s"The id is '$id'")
}
// tests:
Post("/", FormData("color" -> "blue")) ~> route ~> check {
responseAs[String] shouldEqual "The color is 'blue'"
}

View file

@ -44,6 +44,7 @@ class FutureDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/divide/10/2") ~> route ~> check {
responseAs[String] shouldEqual "The result was 5"
}
@ -67,6 +68,7 @@ class FutureDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/success") ~> route ~> check {
responseAs[String] shouldEqual "Ok"
}
@ -90,6 +92,7 @@ class FutureDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/success") ~> route ~> check {
responseAs[String] shouldEqual "Ok"
}

View file

@ -19,6 +19,7 @@ class HeaderDirectivesExamplesSpec extends RoutingSpec with Inside {
complete(s"The user is $userId")
}
// tests:
Get("/") ~> RawHeader("X-User-Id", "Joe42") ~> route ~> check {
responseAs[String] shouldEqual "The user is Joe42"
}
@ -39,6 +40,7 @@ class HeaderDirectivesExamplesSpec extends RoutingSpec with Inside {
complete(s"The port was $port")
}
// tests:
Get("/") ~> Host("example.com", 5043) ~> route ~> check {
responseAs[String] shouldEqual "The port was 5043"
}
@ -67,6 +69,7 @@ class HeaderDirectivesExamplesSpec extends RoutingSpec with Inside {
}
}
// tests:
Get("/") ~> Host("example.com", 5043) ~> route ~> check {
responseAs[String] shouldEqual "The port was 5043"
}
@ -89,6 +92,7 @@ class HeaderDirectivesExamplesSpec extends RoutingSpec with Inside {
}
}
// tests:
Get("/") ~> RawHeader("X-User-Id", "Joe42") ~> route ~> check {
responseAs[String] shouldEqual "The user is Joe42"
}
@ -106,6 +110,7 @@ class HeaderDirectivesExamplesSpec extends RoutingSpec with Inside {
complete(s"The port was $port")
}
// tests:
Get("/") ~> Host("example.com", 5043) ~> route ~> check {
responseAs[String] shouldEqual "The port was 5043"
}
@ -133,6 +138,7 @@ class HeaderDirectivesExamplesSpec extends RoutingSpec with Inside {
}
}
// tests:
Get("/") ~> Host("example.com", 5043) ~> route ~> check {
responseAs[String] shouldEqual "The port was 5043"
}
@ -148,6 +154,7 @@ class HeaderDirectivesExamplesSpec extends RoutingSpec with Inside {
val originHeader = Origin(HttpOrigin("http://localhost:8080"))
// tests:
// extract a header if the type is matching
Get("abc") ~> originHeader ~> route ~> check {
responseAs[String] shouldEqual "The first origin was http://localhost:8080"
@ -166,6 +173,8 @@ class HeaderDirectivesExamplesSpec extends RoutingSpec with Inside {
}
val originHeader = Origin(HttpOrigin("http://localhost:8080"))
// tests:
// extract Some(header) if the type is matching
Get("abc") ~> originHeader ~> route ~> check {
responseAs[String] shouldEqual "The first origin was http://localhost:8080"

View file

@ -17,6 +17,7 @@ class HostDirectivesExamplesSpec extends RoutingSpec {
complete(s"Hostname: $hn")
}
// tests:
Get() ~> Host("company.com", 9090) ~> route ~> check {
status shouldEqual OK
responseAs[String] shouldEqual "Hostname: company.com"
@ -29,6 +30,7 @@ class HostDirectivesExamplesSpec extends RoutingSpec {
complete("Ok")
}
// tests:
Get() ~> Host("rest.company.com") ~> route ~> check {
status shouldEqual OK
responseAs[String] shouldEqual "Ok"
@ -47,6 +49,7 @@ class HostDirectivesExamplesSpec extends RoutingSpec {
complete("Ok")
}
// tests:
Get() ~> Host("short.com") ~> route ~> check {
status shouldEqual OK
responseAs[String] shouldEqual "Ok"
@ -66,6 +69,7 @@ class HostDirectivesExamplesSpec extends RoutingSpec {
complete(s"You came through $captured company")
}
// tests:
Get() ~> Host("api.company.com") ~> route ~> check {
status shouldEqual OK
responseAs[String] shouldEqual "Extracted prefix: api"

View file

@ -6,11 +6,9 @@ package docs.http.scaladsl.server
package directives
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.MediaTypes.`application/json`
import akka.http.scaladsl.model._
import spray.json.DefaultJsonProtocol
import headers._
import StatusCodes._
import MediaTypes.`application/json`
//# person-case-class
case class Person(name: String, favoriteNumber: Int)
@ -32,6 +30,7 @@ class MarshallingDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Post("/", HttpEntity(`application/json`, """{ "name": "Jane", "favoriteNumber" : 42 }""")) ~>
route ~> check {
responseAs[String] shouldEqual "Person: Jane - favorite number: 42"
@ -53,6 +52,7 @@ class MarshallingDirectivesExamplesSpec extends RoutingSpec {
completeWith(instanceOf[Person]) { completionFunction => findPerson(completionFunction) }
}
// tests:
Get("/") ~> route ~> check {
mediaType shouldEqual `application/json`
responseAs[String] should include(""""name": "Jane"""")
@ -75,6 +75,7 @@ class MarshallingDirectivesExamplesSpec extends RoutingSpec {
handleWith(updatePerson)
}
// tests:
Post("/", HttpEntity(`application/json`, """{ "name": "Jane", "favoriteNumber" : 42 }""")) ~>
route ~> check {
mediaType shouldEqual `application/json`

View file

@ -13,6 +13,7 @@ class MethodDirectivesExamplesSpec extends RoutingSpec {
"delete-method" in {
val route = delete { complete("This is a DELETE request.") }
// tests:
Delete("/") ~> route ~> check {
responseAs[String] shouldEqual "This is a DELETE request."
}
@ -21,6 +22,7 @@ class MethodDirectivesExamplesSpec extends RoutingSpec {
"get-method" in {
val route = get { complete("This is a GET request.") }
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "This is a GET request."
}
@ -29,6 +31,7 @@ class MethodDirectivesExamplesSpec extends RoutingSpec {
"head-method" in {
val route = head { complete("This is a HEAD request.") }
// tests:
Head("/") ~> route ~> check {
responseAs[String] shouldEqual "This is a HEAD request."
}
@ -37,6 +40,7 @@ class MethodDirectivesExamplesSpec extends RoutingSpec {
"options-method" in {
val route = options { complete("This is an OPTIONS request.") }
// tests:
Options("/") ~> route ~> check {
responseAs[String] shouldEqual "This is an OPTIONS request."
}
@ -45,6 +49,7 @@ class MethodDirectivesExamplesSpec extends RoutingSpec {
"patch-method" in {
val route = patch { complete("This is a PATCH request.") }
// tests:
Patch("/", "patch content") ~> route ~> check {
responseAs[String] shouldEqual "This is a PATCH request."
}
@ -53,6 +58,7 @@ class MethodDirectivesExamplesSpec extends RoutingSpec {
"post-method" in {
val route = post { complete("This is a POST request.") }
// tests:
Post("/", "post content") ~> route ~> check {
responseAs[String] shouldEqual "This is a POST request."
}
@ -61,6 +67,7 @@ class MethodDirectivesExamplesSpec extends RoutingSpec {
"put-method" in {
val route = put { complete("This is a PUT request.") }
// tests:
Put("/", "put content") ~> route ~> check {
responseAs[String] shouldEqual "This is a PUT request."
}
@ -69,6 +76,7 @@ class MethodDirectivesExamplesSpec extends RoutingSpec {
"method-example" in {
val route = method(HttpMethods.PUT) { complete("This is a PUT request.") }
// tests:
Put("/", "put content") ~> route ~> check {
responseAs[String] shouldEqual "This is a PUT request."
}
@ -88,6 +96,7 @@ class MethodDirectivesExamplesSpec extends RoutingSpec {
complete(s"This ${method.name} request, clearly is not a GET!")
}
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "This is a GET request."
}
@ -111,6 +120,7 @@ class MethodDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/?method=POST") ~> route ~> check {
responseAs[String] shouldEqual "This looks like a POST request."
}

View file

@ -16,6 +16,7 @@ class MiscDirectivesExamplesSpec extends RoutingSpec {
complete("Client's ip is " + ip.toOption.map(_.getHostAddress).getOrElse("unknown"))
}
// tests:
Get("/").withHeaders(`Remote-Address`(RemoteAddress("192.168.3.12"))) ~> route ~> check {
responseAs[String] shouldEqual "Client's ip is 192.168.3.12"
}
@ -32,6 +33,7 @@ class MiscDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/even/23") ~> Route.seal(route) ~> check {
status shouldEqual StatusCodes.NotFound
}
@ -48,6 +50,7 @@ class MiscDirectivesExamplesSpec extends RoutingSpec {
complete("request entity present")
}
// tests:
Post("/", "text") ~> Route.seal(route) ~> check {
responseAs[String] shouldEqual "request entity present"
}
@ -63,6 +66,7 @@ class MiscDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/234") ~> route ~> check {
responseAs[String] shouldEqual "Full URI: http://example.com/234"
}

View file

@ -16,6 +16,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
complete(s"The color is '$color'")
}
// tests:
Get("/?color=blue") ~> route ~> check {
responseAs[String] shouldEqual "The color is 'blue'"
}
@ -31,6 +32,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
complete(s"The color is '$color' and the background is '$backgroundColor'")
}
// tests:
Get("/?color=blue&backgroundColor=red") ~> route ~> check {
responseAs[String] shouldEqual "The color is 'blue' and the background is 'red'"
}
@ -46,6 +48,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
complete(s"The color is '$color' and the background is '$backgroundStr'")
}
// tests:
Get("/?color=blue&backgroundColor=red") ~> route ~> check {
responseAs[String] shouldEqual "The color is 'blue' and the background is 'red'"
}
@ -59,6 +62,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
complete(s"The color is '$color' and the background is '$backgroundColor'")
}
// tests:
Get("/?color=blue&backgroundColor=red") ~> route ~> check {
responseAs[String] shouldEqual "The color is 'blue' and the background is 'red'"
}
@ -72,6 +76,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
complete(s"The color is '$color'.")
}
// tests:
Get("/?color=blue&action=true") ~> route ~> check {
responseAs[String] shouldEqual "The color is 'blue'."
}
@ -87,6 +92,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
complete(s"The color is '$color' and you have $count of it.")
}
// tests:
Get("/?color=blue&count=42") ~> route ~> check {
responseAs[String] shouldEqual "The color is 'blue' and you have 42 of it."
}
@ -106,6 +112,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
}
}
// tests:
Get("/?color=blue") ~> route ~> check {
responseAs[String] === "The color is 'blue' and there are no cities."
}
@ -128,6 +135,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
}
}
// tests:
Get("/?color=blue") ~> route ~> check {
responseAs[String] === "The color is 'blue' and there are no distances."
}
@ -147,6 +155,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
complete(s"The parameters are ${params.map(paramString).mkString(", ")}")
}
// tests:
Get("/?color=blue&count=42") ~> route ~> check {
responseAs[String] shouldEqual "The parameters are color = 'blue', count = '42'"
}
@ -160,6 +169,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
complete(s"There are parameters ${params.map(x => x._1 + " -> " + x._2.size).mkString(", ")}")
}
// tests:
Get("/?color=blue&count=42") ~> route ~> check {
responseAs[String] shouldEqual "There are parameters color -> 1, count -> 1"
}
@ -174,6 +184,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
complete(s"The parameters are ${params.map(paramString).mkString(", ")}")
}
// tests:
Get("/?color=blue&count=42") ~> route ~> check {
responseAs[String] shouldEqual "The parameters are color = 'blue', count = '42'"
}
@ -187,6 +198,7 @@ class ParameterDirectivesExamplesSpec extends RoutingSpec with PredefinedFromStr
complete(s"The parameters are ${names.mkString(", ")}")
}
// tests:
Get("/?names=Caplin") ~> route ~> check {
responseAs[String] shouldEqual "The parameters are Caplin"
}

View file

@ -66,6 +66,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/") ~> route ~> check {
handled shouldEqual false
}
@ -94,6 +95,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/foo") ~> route ~> check {
responseAs[String] shouldEqual "/foo"
}
@ -118,6 +120,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/foo") ~> route ~> check {
responseAs[String] shouldEqual "/foo"
}
@ -142,6 +145,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/") ~> route ~> check {
handled shouldEqual false
}
@ -162,6 +166,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
pathPrefix("bar") { completeWithUnmatchedPath }
}
// tests:
Get("/foo/doo") ~> route ~> check {
responseAs[String] shouldEqual "/doo"
}
@ -185,6 +190,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "root"
}
@ -213,6 +219,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/start/middle/end") ~> route ~> check {
responseAs[String] shouldEqual "/middle/"
}
@ -229,6 +236,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
} ~
complete("unslashed")
// tests:
Get("/foo/") ~> route ~> check {
responseAs[String] shouldEqual "slashed"
}
@ -244,6 +252,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
rawPathPrefix("doo") { completeWithUnmatchedPath }
}
// tests:
Get("/foobar/baz") ~> route ~> check {
responseAs[String] shouldEqual "/baz"
}
@ -261,6 +270,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/foobar") ~> route ~> check {
responseAs[String] shouldEqual "bar"
}
@ -293,6 +303,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
// Redirected:
Get("/foo") ~> route ~> check {
status shouldEqual StatusCodes.MovedPermanently
@ -342,6 +353,7 @@ class PathDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
// Redirected:
Get("/foo/") ~> route ~> check {
status shouldEqual StatusCodes.MovedPermanently

View file

@ -1,37 +1,38 @@
/*
* Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
*/
package docs.http.scaladsl.server
package directives
/*
import akka.http.scaladsl.model._
import headers._
class RangeDirectivesExamplesSpec extends RoutingSpec {
"withRangeSupport" in {
val route =
withRangeSupport(4, 2L) {
complete("ABCDEFGH")
}
Get() ~> addHeader(Range(ByteRange(3, 4))) ~> route ~> check {
headers must contain(`Content-Range`(ContentRange(3, 4, 8)))
status shouldEqual StatusCodes.PartialContent
responseAs[String] shouldEqual "DE"
}
Get() ~> addHeader(Range(ByteRange(0, 1), ByteRange(1, 2), ByteRange(6, 7))) ~> route ~> check {
headers must not(contain(like[HttpHeader] { case `Content-Range`(_, _) ok }))
responseAs[MultipartByteRanges] must beLike {
case MultipartByteRanges(
BodyPart(entity1, `Content-Range`(RangeUnit.Bytes, range1) +: _) +:
BodyPart(entity2, `Content-Range`(RangeUnit.Bytes, range2) +: _) +: Seq()
) entity1.asString shouldEqual "ABC" and range1 shouldEqual ContentRange(0, 2, 8) and
entity2.asString shouldEqual "GH" and range2 shouldEqual ContentRange(6, 7, 8)
}
}
}
}
*/
///*
// * Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
// */
//
//package docs.http.scaladsl.server
//package directives
//
//import akka.http.javadsl.model.headers.RangeUnit
//import akka.http.scaladsl.model.Multipart.ByteRanges.BodyPart
//import akka.http.scaladsl.model._
//import headers._
//
//class RangeDirectivesExamplesSpec extends RoutingSpec {
//
// "withRangeSupport" in {
// val route =
// withRangeSupport {
// complete("ABCDEFGH")
// }
//
// Get() ~> addHeader(Range(ByteRange(3, 4))) ~> route ~> check {
// headers should contain(`Content-Range`(ContentRange(3, 4, 8)))
// status shouldEqual StatusCodes.PartialContent
// responseAs[String] shouldEqual "DE"
// }
//
// Get() ~> addHeader(Range(ByteRange(0, 1), ByteRange(1, 2), ByteRange(6, 7))) ~> route ~> check {
// headers must not(contain(like[HttpHeader] { case `Content-Range`(_, _) ok }))
// responseAs[MultipartByteRanges] must beLike {
// case MultipartByteRanges(
// BodyPart(entity1, `Content-Range`(RangeUnits.Bytes, range1) +: _) +:
// BodyPart(entity2, `Content-Range`(RangeUnits.Bytes, range2) +: _) +: Seq()
// ) entity1.asString shouldEqual "ABC" and range1 shouldEqual ContentRange(0, 2, 8) and
// entity2.asString shouldEqual "GH" and range2 shouldEqual ContentRange(6, 7, 8)
// }
// }
// }
//}

View file

@ -17,6 +17,7 @@ class RespondWithDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/foo") ~> route ~> check {
header("Funky-Muppet") shouldEqual Some(RawHeader("Funky-Muppet", "gonzo"))
responseAs[String] shouldEqual "beep"
@ -45,6 +46,7 @@ class RespondWithDirectivesExamplesSpec extends RoutingSpec {
} // x
// format: ON
// tests:
Get("/") ~> route ~> check {
header("X-Fish-Name") shouldEqual Some(RawHeader("X-Fish-Name", "Blippy"))
responseAs[String] shouldEqual "Blip!"
@ -70,6 +72,7 @@ class RespondWithDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/foo") ~> route ~> check {
header("Funky-Muppet") shouldEqual Some(RawHeader("Funky-Muppet", "gonzo"))
header[Origin] shouldEqual Some(Origin(HttpOrigin("http://akka.io")))
@ -77,54 +80,4 @@ class RespondWithDirectivesExamplesSpec extends RoutingSpec {
}
}
// FIXME awaiting resolution of https://github.com/akka/akka/issues/18625
// "respondWithMediaType-examples" in {
// import MediaTypes._
//
// val route =
// path("foo") {
// respondWithMediaType(`application/json`) {
// complete("[]") // marshalled to `text/plain` here
// }
// }
//
// Get("/foo") ~> route ~> check {
// mediaType shouldEqual `application/json`
// responseAs[String] shouldEqual "[]"
// }
//
// Get("/foo") ~> Accept(MediaRanges.`text/*`) ~> route ~> check {
// rejection shouldEqual UnacceptedResponseContentTypeRejection(ContentType(`application/json`) :: Nil)
// }
// }
// "respondWithSingletonHeader-examples" in {
// val respondWithMuppetHeader =
// respondWithSingletonHeader(RawHeader("Funky-Muppet", "gonzo"))
//
// val route =
// path("foo") {
// respondWithMuppetHeader {
// complete("beep")
// }
// } ~
// path("bar") {
// respondWithMuppetHeader {
// respondWithHeader(RawHeader("Funky-Muppet", "kermit")) {
// complete("beep")
// }
// }
// }
//
// Get("/foo") ~> route ~> check {
// headers.filter(_.is("funky-muppet")) shouldEqual List(RawHeader("Funky-Muppet", "gonzo"))
// responseAs[String] shouldEqual "beep"
// }
//
// Get("/bar") ~> route ~> check {
// headers.filter(_.is("funky-muppet")) shouldEqual List(RawHeader("Funky-Muppet", "kermit"))
// responseAs[String] shouldEqual "beep"
// }
// }
}

View file

@ -20,6 +20,7 @@ class RouteDirectivesExamplesSpec extends RoutingSpec {
} ~
(path("c") & complete("baz")) // `&` also works with `complete` as the 2nd argument
// tests:
Get("/a") ~> route ~> check {
status shouldEqual StatusCodes.OK
responseAs[String] shouldEqual "foo"
@ -50,6 +51,7 @@ class RouteDirectivesExamplesSpec extends RoutingSpec {
reject(ValidationRejection("Restricted!"))
}
// tests:
Get("/a") ~> route ~> check {
responseAs[String] shouldEqual "foo"
}
@ -70,6 +72,7 @@ class RouteDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/foo/") ~> route ~> check {
responseAs[String] shouldEqual "yes"
}
@ -86,6 +89,7 @@ class RouteDirectivesExamplesSpec extends RoutingSpec {
failWith(new RuntimeException("Oops."))
}
// tests:
Get("/foo") ~> Route.seal(route) ~> check {
status shouldEqual StatusCodes.InternalServerError
responseAs[String] shouldEqual "There was an internal server error."

View file

@ -12,6 +12,7 @@ class SchemeDirectivesExamplesSpec extends RoutingSpec {
complete(s"The scheme is '${scheme}'")
}
// tests:
Get("https://www.example.com/") ~> route ~> check {
responseAs[String] shouldEqual "The scheme is 'https'"
}
@ -32,6 +33,7 @@ class SchemeDirectivesExamplesSpec extends RoutingSpec {
complete(s"Safe and secure!")
}
// tests:
Get("http://www.example.com/hello") ~> route ~> check {
status shouldEqual MovedPermanently
header[Location] shouldEqual Some(Location(Uri("https://www.example.com/hello")))

View file

@ -30,6 +30,7 @@ class SecurityDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/secured") ~> route ~> check {
status shouldEqual StatusCodes.Unauthorized
responseAs[String] shouldEqual "The resource requires authentication, which was not supplied with the request"
@ -66,6 +67,7 @@ class SecurityDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/secured") ~> route ~> check {
status shouldEqual StatusCodes.Unauthorized
responseAs[String] shouldEqual "The resource requires authentication, which was not supplied with the request"
@ -114,6 +116,7 @@ class SecurityDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/secured") ~> route ~> check {
status shouldEqual StatusCodes.Unauthorized
responseAs[String] shouldEqual "The resource requires authentication, which was not supplied with the request"
@ -156,6 +159,7 @@ class SecurityDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/secured") ~> route ~> check {
status shouldEqual StatusCodes.Unauthorized
responseAs[String] shouldEqual "The resource requires authentication, which was not supplied with the request"
@ -200,6 +204,7 @@ class SecurityDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
Get("/secured") ~> route ~> check {
status shouldEqual StatusCodes.Unauthorized
responseAs[String] shouldEqual "The resource requires authentication, which was not supplied with the request"
@ -240,6 +245,7 @@ class SecurityDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
val johnsCred = BasicHttpCredentials("John", "p4ssw0rd")
Get("/peters-lair") ~> addCredentials(johnsCred) ~> // adds Authorization header
route ~> check {
@ -265,6 +271,7 @@ class SecurityDirectivesExamplesSpec extends RoutingSpec {
}
}
// tests:
val johnsCred = BasicHttpCredentials("John", "p4ssw0rd")
Get("/") ~> addCredentials(johnsCred) ~> // adds Authorization header
route ~> check {

View file

@ -32,6 +32,7 @@ class WebsocketDirectivesExamplesSpec extends RoutingSpec {
handleWebsocketMessages(greeter)
}
// tests:
// create a testing probe representing the client-side
val wsClient = WSProbe()
@ -78,6 +79,7 @@ class WebsocketDirectivesExamplesSpec extends RoutingSpec {
handleWebsocketMessagesForProtocol(echoService, "echo")
}
// tests:
val wsClient = WSProbe()
// WS creates a Websocket request for testing

View file

@ -5,3 +5,6 @@ Migration Guide from spray
- ``respondWithStatus`` also known as ``overrideStatusCode`` has not been forward ported to Akka HTTP,
as it has been seen mostly as an anti-pattern. More information here: https://github.com/akka/akka/issues/18626
- ``respondWithMediaType`` was considered an anti-pattern in spray and is not ported to Akka HTTP.
Instead users should rely on content type negotiation as Akka HTTP implements it.
More information here: https://github.com/akka/akka/issues/18625

View file

@ -3,9 +3,6 @@
cancelRejection
===============
Adds a ``TransformationRejection`` cancelling all rejections equal to the
given one to the rejections potentially coming back from the inner route.
Signature
---------
@ -15,10 +12,14 @@ Signature
Description
-----------
Cancels a rejection which may potentially come back from the inner route.
Adds a ``TransformationRejection`` cancelling all rejections equal to the
given one to the rejections potentially coming back from the inner route.
Read :ref:`rejections-scala` to learn more about rejections.
For more advanced handling of rejections refer to the :ref:`-handleRejections-` directive
which provides a nicer DSL for building rejection handlers.
Example
-------

View file

@ -3,9 +3,6 @@
cancelRejections
================
Adds a ``TransformationRejection`` cancelling all matching rejections
to the rejections potentially coming back from the inner route
Signature
---------
@ -15,12 +12,16 @@ Signature
Description
-----------
Cancels all rejections created by the inner route for which the condition argument function returns ``true``.
Adds a ``TransformationRejection`` cancelling all rejections created by the inner route for which
the condition argument function returns ``true``.
See also :ref:`-cancelRejection-`, for canceling a specific rejection.
Read :ref:`rejections-scala` to learn more about rejections.
For more advanced handling of rejections refer to the :ref:`-handleRejections-` directive
which provides a nicer DSL for building rejection handlers.
Example
-------

View file

@ -3,8 +3,6 @@
extract
=======
Calculates a value from the request context and provides the value to the inner route.
Signature
---------

View file

@ -3,8 +3,6 @@
extractExecutionContext
=======================
...
Signature
---------
@ -14,10 +12,14 @@ Signature
Description
-----------
...
Extracts the ``ExecutionContext`` from the ``RequestContext``.
See :ref:`-withExecutionContext-` to see how to customise the execution context provided for an inner route.
See :ref:`-extract-` to learn more about how extractions work.
Example
-------
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
:snippet: 0extractExecutionContext
:snippet: extractExecutionContext-0

View file

@ -3,8 +3,6 @@
extractLog
==========
Extracts a :class:`LoggingAdapter` from the request context which can be used for logging inside the route.
Signature
---------
@ -14,6 +12,8 @@ Signature
Description
-----------
Extracts a :class:`LoggingAdapter` from the request context which can be used for logging inside the route.
The ``extractLog`` directive is used for providing logging to routes, such that they don't have to depend on
closing over a logger provided in the class body.

View file

@ -1,9 +1,7 @@
.. _-extractMaterializer-:
extractMaterializer
=======================
...
===================
Signature
---------
@ -14,10 +12,13 @@ Signature
Description
-----------
...
Extracts the ``Materializer`` from the ``RequestContext``, which can be useful when you want to run an
Akka Stream directly in your route.
See also :ref:`-withMaterializer-` to see how to customise the used materializer for specific inner routes.
Example
-------
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
:snippet: 0extractMaterializer
:snippet: extractMaterializer-0

View file

@ -3,8 +3,6 @@
extractRequest
==============
Extracts the complete ``HttpRequest`` instance.
Signature
---------
@ -13,6 +11,7 @@ Signature
Description
-----------
Extracts the complete ``HttpRequest`` instance.
Use ``extractRequest`` to extract just the complete URI of the request. Usually there's little use of
extracting the complete request because extracting of most of the aspects of HttpRequests is handled by specialized

View file

@ -3,12 +3,6 @@
extractRequestContext
=====================
Extracts the request's underlying :class:`RequestContext`.
This directive is used as a building block for most of the other directives,
which extract the context and by inspecting some of it's values can decide
what to do with the request - for example provide a value, or reject the request.
Signature
---------
@ -18,10 +12,16 @@ Signature
Description
-----------
...
Extracts the request's underlying :class:`RequestContext`.
This directive is used as a building block for most of the other directives,
which extract the context and by inspecting some of it's values can decide
what to do with the request - for example provide a value, or reject the request.
See also :ref:`-extractRequest-` if only interested in the :class:`HttpRequest` instance itself.
Example
-------
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
:snippet: 0extractRequestContext
:snippet: extractRequestContext-example

View file

@ -3,8 +3,6 @@
extractSettings
===============
Extracts the ``RoutingSettings`` from the :class:`RequestContext`.
Signature
---------
@ -23,4 +21,4 @@ Example
-------
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
:snippet: 0extractSettings
:snippet: extractSettings-examples

View file

@ -3,8 +3,6 @@
extractUnmatchedPath
====================
Extracts the unmatched path from the request context.
Signature
---------
@ -13,6 +11,7 @@ Signature
Description
-----------
Extracts the unmatched path from the request context.
The ``extractUnmatchedPath`` directive extracts the remaining path that was not yet matched by any of the :ref:`PathDirectives`
(or any custom ones that change the unmatched path field of the request context). You can use it for building directives

View file

@ -3,8 +3,6 @@
extractUri
==========
Access the full URI of the request.
Signature
---------
@ -13,6 +11,7 @@ Signature
Description
-----------
Access the full URI of the request.
Use :ref:`SchemeDirectives`, :ref:`HostDirectives`, :ref:`PathDirectives`, and :ref:`ParameterDirectives` for more
targeted access to parts of the URI.

View file

@ -3,8 +3,6 @@
mapInnerRoute
=============
Changes the execution model of the inner route by wrapping it with arbitrary logic.
Signature
---------
@ -13,6 +11,7 @@ Signature
Description
-----------
Changes the execution model of the inner route by wrapping it with arbitrary logic.
The ``mapInnerRoute`` directive is used as a building block for :ref:`Custom Directives` to replace the inner route
with any other route. Usually, the returned route wraps the original one with custom execution logic.

View file

@ -3,8 +3,6 @@
mapRejections
=============
Transforms the list of rejections the inner route produced.
Signature
---------
@ -14,6 +12,9 @@ Signature
Description
-----------
**Low level directive** unless you're sure you need to be working on this low-level you might instead
want to try the :ref:`-handleRejections-` directive which provides a nicer DSL for building rejection handlers.
The ``mapRejections`` directive is used as a building block for :ref:`Custom Directives` to transform a list
of rejections from the inner route to a new list of rejections.

View file

@ -3,8 +3,6 @@
mapRequest
==========
Transforms the request before it is handled by the inner route.
Signature
---------
@ -13,6 +11,7 @@ Signature
Description
-----------
Transforms the request before it is handled by the inner route.
The ``mapRequest`` directive is used as a building block for :ref:`Custom Directives` to transform a request before it
is handled by the inner route. Changing the ``request.uri`` parameter has no effect on path matching in the inner route

View file

@ -3,8 +3,6 @@
mapRequestContext
=================
Transforms the ``RequestContext`` before it is passed to the inner route.
Signature
---------
@ -13,6 +11,7 @@ Signature
Description
-----------
Transforms the ``RequestContext`` before it is passed to the inner route.
The ``mapRequestContext`` directive is used as a building block for :ref:`Custom Directives` to transform
the request context before it is passed to the inner route. To change only the request value itself the

View file

@ -3,8 +3,6 @@
mapResponse
===========
Changes the response that was generated by the inner route.
Signature
---------

View file

@ -3,8 +3,6 @@
mapResponseEntity
=================
Changes the response entity that was generated by the inner route.
Signature
---------

View file

@ -3,8 +3,6 @@
mapResponseHeaders
==================
Changes the list of response headers that was generated by the inner route.
Signature
---------
@ -13,6 +11,7 @@ Signature
Description
-----------
Changes the list of response headers that was generated by the inner route.
The ``mapResponseHeaders`` directive is used as a building block for :ref:`Custom Directives` to transform the list of
response headers that was generated by the inner route.

View file

@ -3,8 +3,6 @@
mapRouteResult
==============
Changes the message the inner route sends to the responder.
Signature
---------
@ -13,6 +11,7 @@ Signature
Description
-----------
Changes the message the inner route sends to the responder.
The ``mapRouteResult`` directive is used as a building block for :ref:`Custom Directives` to transform the
:ref:`RouteResult` coming back from the inner route.

View file

@ -3,8 +3,6 @@
mapRouteResultFuture
====================
...
Signature
---------
@ -14,10 +12,16 @@ Signature
Description
-----------
...
Asynchronous version of :ref:`-mapRouteResult-`.
It's similar to :ref:`-mapRouteResultWith-`, however it's ``Future[RouteResult] ⇒ Future[RouteResult]``
instead of ``RouteResult ⇒ Future[RouteResult]`` which may be useful when combining multiple transformantions
and / or wanting to ``recover`` from a failed route result.
See :ref:`Result Transformation Directives` for similar directives.
Example
-------
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
:snippet: 0mapRouteResultFuture
:snippet: mapRouteResultFuture

View file

@ -3,8 +3,6 @@
mapRouteResultPF
================
Changes the message the inner route sends to the responder.
Signature
---------
@ -13,6 +11,9 @@ Signature
Description
-----------
*Partial Function* version of :ref:`-mapRouteResult-`.
Changes the message the inner route sends to the responder.
The ``mapRouteResult`` directive is used as a building block for :ref:`Custom Directives` to transform the
:ref:`RouteResult` coming back from the inner route. It's similar to the :ref:`-mapRouteResult-` directive but allows to

View file

@ -3,8 +3,6 @@
mapRouteResultWith
==================
...
Signature
---------
@ -14,10 +12,16 @@ Signature
Description
-----------
...
Changes the message the inner route sends to the responder.
The ``mapRouteResult`` directive is used as a building block for :ref:`Custom Directives` to transform the
:ref:`RouteResult` coming back from the inner route. It's similar to the :ref:`-mapRouteResult-` directive but
returning a ``Future`` instead of a result immediadly, which may be useful for longer running transformations.
See :ref:`Result Transformation Directives` for similar directives.
Example
-------
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
:snippet: 0mapRouteResultWith
:snippet: mapRouteResultWith-0

View file

@ -3,8 +3,6 @@
mapRouteResultWithPF
====================
...
Signature
---------
@ -14,10 +12,17 @@ Signature
Description
-----------
...
Asynchronous variant of :ref:`mapRouteResultPF`.
Changes the message the inner route sends to the responder.
The ``mapRouteResult`` directive is used as a building block for :ref:`Custom Directives` to transform the
:ref:`RouteResult` coming back from the inner route.
See :ref:`Result Transformation Directives` for similar directives.
Example
-------
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
:snippet: 0mapRouteResultWithPF
:snippet: mapRouteResultWithPF-0

View file

@ -3,8 +3,6 @@
mapSettings
===========
...
Signature
---------
@ -14,10 +12,12 @@ Signature
Description
-----------
...
Transforms the ``RoutingSettings`` with a ``RoutingSettings ⇒ RoutingSettings`` function.
See also :ref:`-withSettings-` or :ref:`-extractSettings-`.
Example
-------
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
:snippet: 0mapSettings
:snippet: withSettings-0

View file

@ -3,8 +3,6 @@
mapUnmatchedPath
================
Transforms the unmatchedPath field of the request context for inner routes.
Signature
---------
@ -13,6 +11,7 @@ Signature
Description
-----------
Transforms the unmatchedPath field of the request context for inner routes.
The ``mapUnmatchedPath`` directive is used as a building block for writing :ref:`Custom Directives`. You can use it
for implementing custom path matching directives.

View file

@ -3,8 +3,6 @@
pass
====
A directive that passes the request unchanged to its inner route.
Signature
---------
@ -13,8 +11,10 @@ Signature
Description
-----------
A directive that passes the request unchanged to its inner route.
The directive is usually used as a "neutral element" when combining directives generically.
It is usually used as a "neutral element" when combining directives generically.
Example

View file

@ -3,8 +3,6 @@
provide
=======
Provides a constant value to the inner route.
Signature
---------
@ -13,6 +11,7 @@ Signature
Description
-----------
Provides a constant value to the inner route.
The `provide` directive is used as a building block for :ref:`Custom Directives` to provide a single value to the
inner route. To provide several values use the :ref:`-tprovide-` directive.

View file

@ -3,8 +3,6 @@
recoverRejections
=================
Transforms rejections from the inner route with an ``immutable.Seq[Rejection] ⇒ RouteResult`` function.
Signature
---------
@ -17,8 +15,8 @@ Description
**Low level directive** unless you're sure you need to be working on this low-level you might instead
want to try the :ref:`-handleRejections-` directive which provides a nicer DSL for building rejection handlers.
Transforms rejections from the inner route to a ``RouteResult`` either a ``Complete(HttpResponse(...))``
or more rejections: ``Rejected(rejections)``.
Transforms rejections from the inner route with an ``immutable.Seq[Rejection] ⇒ RouteResult`` function.
A ``RouteResult`` is either a ``Complete(HttpResponse(...))`` or rejections ``Rejected(rejections)``.
.. note::
To learn more about how and why rejections work read the :ref:`rejections-scala` section of the documentation.

View file

@ -24,4 +24,4 @@ Example
-------
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
:snippet: 0withExecutionContext
:snippet: withExecutionContext-0

View file

@ -24,4 +24,4 @@ Example
-------
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
:snippet: 0withMaterializer
:snippet: withMaterializer-0

View file

@ -23,4 +23,4 @@ Example
-------
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
:snippet: 0withSettings
:snippet: withSettings-0

View file

@ -3,8 +3,6 @@
handleRejections
================
Handles rejections produced by the inner route and handles them using the specified ``RejectionHandler``.
Signature
---------