Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get http request header info from the server side with spray RestAPI

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.

like image 970
Janaka Priyadarshana Avatar asked Jan 07 '23 13:01

Janaka Priyadarshana


2 Answers

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")
}
like image 173
Gabriele Petronella Avatar answered Jan 15 '23 11:01

Gabriele Petronella


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")
}
like image 25
jasop Avatar answered Jan 15 '23 11:01

jasop