withSettings

Signature

def withSettings(settings: RoutingSettings): Directive0

Description

Allows running an inner route using an alternative RoutingSettingsRoutingSettings in place of the default one.

The execution context can be extracted in an inner route using extractSettings directly, or used by directives which internally extract the materializer without surfacing this fact in the API.

Example

Scala
val special = RoutingSettings(system).withFileIODispatcher("special-io-dispatcher")

def sample() =
  path("sample") {
    complete {
      // internally uses the configured fileIODispatcher:
      val source = FileIO.fromPath(Paths.get("example.json"))
      HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, source))
    }
  }

val route =
  get {
    pathPrefix("special") {
      withSettings(special) {
        sample() // `special` file-io-dispatcher will be used to read the file
      }
    } ~ sample() // default file-io-dispatcher will be used to read the file
  }

// tests:
Post("/special/sample") ~> route ~> check {
  responseAs[String] shouldEqual s"{}"
}
Get("/sample") ~> route ~> check {
  responseAs[String] shouldEqual "{}"
}
Java
final RoutingSettings special =
  RoutingSettings
    .create(system().settings().config())
    .withFileIODispatcher("special-io-dispatcher");

final Route sample = path("sample", () -> {
  // internally uses the configured fileIODispatcher:
  // ContentTypes.APPLICATION_JSON, source
  final Source<ByteString, Object> source =
    FileIO.fromPath(Paths.get("example.json"))
      .mapMaterializedValue(completionStage -> (Object) completionStage);
  return complete(
    HttpResponse.create()
      .withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, source))
  );
});

final Route route = get(() ->
  route(
    pathPrefix("special", () ->
      // `special` file-io-dispatcher will be used to read the file
      withSettings(special, () -> sample)
    ),
    sample // default file-io-dispatcher will be used to read the file
  )
);

// tests:
testRoute(route).run(HttpRequest.GET("/special/sample"))
  .assertEntity("{}");
testRoute(route).run(HttpRequest.GET("/sample"))
  .assertEntity("{}");
The source code for this page can be found here.