mapResponseHeaders

Signature

def mapResponseHeaders(f: immutable.Seq[HttpHeader] 

Description

Changes the list of response headers that was generated by the inner route.

The mapResponseHeaders directive is used as a building block for Custom Directives to transform the list of response headers that was generated by the inner route.

See Response Transforming Directives for similar directives.

Example

Scala
source// adds all request headers to the response
val echoRequestHeaders = extract(_.request.headers).flatMap(respondWithHeaders)

val removeIdHeader = mapResponseHeaders(_.filterNot(_.lowercaseName == "id"))
val route =
  removeIdHeader {
    echoRequestHeaders {
      complete("test")
    }
  }

// tests:
Get("/") ~> RawHeader("id", "12345") ~> RawHeader("id2", "67890") ~> route ~> check {
  header("id") shouldEqual None
  header("id2").get.value shouldEqual "67890"
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.mapResponseHeaders;

import static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.respondWithHeaders;
import static org.apache.pekko.http.javadsl.server.Directives.mapResponseHeaders;

// adds all request headers to the response
final Route echoRequestHeaders =
    extract(
        ctx -> ctx.getRequest().getHeaders(),
        headers -> respondWithHeaders(headers, () -> complete("test")));

final Route route =
    mapResponseHeaders(
        headers -> {
          headers.removeIf(header -> header.lowercaseName().equals("id"));
          return headers;
        },
        () -> echoRequestHeaders);

// tests:
testRoute(route)
    .run(
        HttpRequest.GET("/")
            .withHeaders(
                Arrays.asList(
                    RawHeader.create("id", "12345"), RawHeader.create("id2", "67890"))))
    .assertHeaderKindNotExists("id")
    .assertHeaderExists("id2", "67890");