respondWithDefaultHeader

respondWithDefaultHeader

§Signature

§Description

Adds a given HTTP header to all responses coming back from its inner route only if a header with the same name doesn't exist yet in the response.

This directive transforms HttpResponse and ChunkedResponseStart messages coming back from its inner route by potentially adding the given HttpHeader instance to the headers list. The header is only added if there is no header instance with the same name (case insensitively) already present in the response.

See also respondWithDefaultHeaders if you'd like to add more than one header.

§Example

  1. // custom headers
  2. val blippy = RawHeader("X-Fish-Name", "Blippy")
  3. val elTonno = RawHeader("X-Fish-Name", "El Tonno")
  4.  
  5. // format: OFF
  6. // by default always include the Blippy header,
  7. // unless a more specific X-Fish-Name is given by the inner route
  8. val route =
  9. respondWithDefaultHeader(blippy) { // blippy
  10. respondWithHeader(elTonno) { // / el tonno
  11. path("el-tonno") { // | /
  12. complete("¡Ay blippy!") // | |- el tonno
  13. } ~ // | |
  14. path("los-tonnos") { // | |
  15. complete("¡Ay ay blippy!") // | |- el tonno
  16. } // | |
  17. } ~ // | x
  18. complete("Blip!") // |- blippy
  19. } // x
  20. // format: ON
  21.  
  22. // tests:
  23. Get("/") ~> route ~> check {
  24. header("X-Fish-Name") shouldEqual Some(RawHeader("X-Fish-Name", "Blippy"))
  25. responseAs[String] shouldEqual "Blip!"
  26. }
  27.  
  28. Get("/el-tonno") ~> route ~> check {
  29. header("X-Fish-Name") shouldEqual Some(RawHeader("X-Fish-Name", "El Tonno"))
  30. responseAs[String] shouldEqual "¡Ay blippy!"
  31. }
  32.  
  33. Get("/los-tonnos") ~> route ~> check {
  34. header("X-Fish-Name") shouldEqual Some(RawHeader("X-Fish-Name", "El Tonno"))
  35. responseAs[String] shouldEqual "¡Ay ay blippy!"
  36. }