extractMethod
Signature
Description
Extracts the HttpMethod
from the request context and provides it for use for other directives explicitly.
Example
In the below example our route first matches all GET
requests, and if an incoming request wasn't a GET
,
the matching continues and the extractMethod route will be applied which we can use to programatically
print what type of request it was - independent of what actual HttpMethod it was:
val route =
get {
complete("This is a GET request.")
} ~
extractMethod { method =>
complete(s"This ${method.name} request, clearly is not a GET!")
}
// tests:
Get("/") ~> route ~> check {
responseAs[String] shouldEqual "This is a GET request."
}
Put("/") ~> route ~> check {
responseAs[String] shouldEqual "This PUT request, clearly is not a GET!"
}
Head("/") ~> route ~> check {
responseAs[String] shouldEqual "This HEAD request, clearly is not a GET!"
}
Custom Http Method
When you define a custom HttpMethod, you can define a route using extractMethod.
import akka.http.scaladsl.settings.{ ParserSettings, ServerSettings }
// define custom media type:
val BOLT = HttpMethod.custom("BOLT", safe = false,
idempotent = true, requestEntityAcceptance = Expected)
// add custom method to parser settings:
val parserSettings = ParserSettings(system).withCustomMethods(BOLT)
val serverSettings = ServerSettings(system).withParserSettings(parserSettings)
val routes = extractMethod { method ⇒
complete(s"This is a ${method.name} method request.")
}
val binding = Http().bindAndHandle(routes, host, port, settings = serverSettings)
Contents