handle

Signature

def handle(handler: HttpRequest => Future[HttpResponse]): StandardRoute
def handle(handler: PartialFunction[HttpRequest, Future[HttpResponse]]): StandardRoute
def handle(handler: PartialFunction[HttpRequest, Future[HttpResponse]], rejections: Seq[Rejection]): StandardRoute

Description

Creates a RouteRoute that handles the request using a function or PartialFunction from HttpRequestHttpRequest to a FutureCompletionStage of HttpResponseHttpResponse.

This directive can be used to include external components request processing components defined as a Function or PartialFunction (like those provided by akka-grpc) into a routing tree defined by directives and routes.

For the PartialFunction variant, the given list of rejections will be used to reject the request with if the PartialFunction is not defined for a request. By default, an empty list of rejections will be used which is interpreted as “Not Found”.

There is also a strict version called handleSync.

Example

Scala
val handler: PartialFunction[HttpRequest, Future[HttpResponse]] = {
  case HttpRequest(HttpMethods.GET, Uri.Path("/value"), _, _, _) =>
    Future.successful(HttpResponse(entity = "23"))
}

val route =
  concat(
    handle(handler),
    complete("fallback")
  )

// tests:
Get("/value") ~> route ~> check {
  status shouldEqual StatusCodes.OK
  responseAs[String] shouldEqual "23"
}

// Uri doesn't match so function is never invoked and the request is rejected and the
// fallback completes the request.
Get("/other") ~> route ~> check {
  status shouldEqual StatusCodes.OK
  responseAs[String] shouldEqual "fallback"
}
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.