extractRequestContext

Signature

def extractRequestContext: Directive1[RequestContext] 

Description

Extracts the request’s underlying RequestContextRequestContext.

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 extractRequest if only interested in the HttpRequestHttpRequest instance itself.

Example

Scala
sourceval route =
  extractRequestContext { ctx =>
    ctx.log.debug("Using access to additional context available, 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"
}
Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "Request method is GET and content-type is none/none"
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.extractRequestContext;

final Route route =
    extractRequestContext(
        ctx -> {
          ctx.getLog().debug("Using access to additional context available, like the logger.");
          final HttpRequest request = ctx.getRequest();
          return complete(
              "Request method is "
                  + request.method().name()
                  + " and content-type is "
                  + request.entity().getContentType());
        });

// tests:
testRoute(route)
    .run(HttpRequest.POST("/").withEntity("text"))
    .assertEntity("Request method is POST and content-type is text/plain; charset=UTF-8");
testRoute(route)
    .run(HttpRequest.GET("/"))
    .assertEntity("Request method is GET and content-type is none/none");