4

I am new to Scala and Spray. I have written a simple REST API according to the instructions given in this blog post. http://www.smartjava.org/content/first-steps-rest-spray-and-scala

And all are working as expected.

Now I want to modify the program to print the HTTP headers like Encoding, Language, remote-address, etc.. I would like to print all the header information (purpose is to log these information)

But I could not find a proper documentation or examples. Could anyone please help me to get this done.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
  • Hi, Still I could not find a way to print all the http headers. In java we can get it as a collection and looping through it and print all. `I am just wondering why it is so hard with spray and scala ???` – Janaka Priyadarshana Sep 16 '15 at 06:39

2 Answers2

7

If you need to extract a specific header:

optionalHeaderValueByName("Encoding") { encodingHeader =>
  println(encodingHeader)
  complete("hello")
}

alternatively you can access the raw request object and directly extractive the headers. Here's a custom directive that logs all the headers:

def logHeaders(): Directive0 = extract(_.request.headers).map(println)

Usage

logHeaders() {
  complete("hello")
}
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
  • Thanks for quick answer. For me the first way is working. But I would prefer the alternative way, and it gives a syntax error with calling 'foreach' -------Error:(37, 61) value foreach is not a member of spray.routing.Directive1[List[spray.http.HttpHeader]] def logHeaders(): Directive0 = extract(_.request.headers).foreach(println)--------- – Janaka Priyadarshana Sep 15 '15 at 05:37
  • woops, try `map` instead of `foreach` – Gabriele Petronella Sep 15 '15 at 10:05
  • map does not help either. I get compilation error as -------Error:(42, 51) value foreach is not a member of spray.routing.Directive1[List[spray.http.HttpHeader]] def logHeaders1() = extract(_.request.headers).foreach(println)----- The above is the error I got, unfortunately I couldn't get the list from spray.routing.Directive1 – Janaka Priyadarshana Sep 15 '15 at 11:55
  • How can you have a `foreach` error if you're using `map`? – Gabriele Petronella Sep 15 '15 at 11:59
  • map didn't do anything for me. So Still I am struggling with foreach. Is map work for you ? – Janaka Priyadarshana Sep 15 '15 at 12:10
  • if I can get the `List[spray.http.HttpHeader]` from the `spray.routing.Directive1[List[spray.http.HttpHeader]]`, I will be able to use `foreach`. How can I get something out from `spray.routing.Directive1` – Janaka Priyadarshana Sep 15 '15 at 12:17
2

Here's how I got it working.

Directive:

def logHeaders(innerRoute: Route): (RequestContext => Unit) = extract(_.request.headers) { headers =>
  headers.foreach(h => logger.info("header: {} = {}", h.name, h.value))
  innerRoute
}

Usage:

logHeaders() {
  complete("hello")
}
mirelon
  • 4,896
  • 6
  • 40
  • 70
jasop
  • 892
  • 11
  • 13