Get http headers with akka routing dsl

I’m new to Scala, and this problem frustrates me. How can I get all headers from request?

val route =  {
  path("lol") {
    //get httpHeaders
    complete(HttpResponse())
  }
}

Answer

You have at least two options here:

a) Using extractRequest directive:

val route = {
  path("example") {
    extractRequest { request =>
      request.headers // Returns `Seq[HttpHeader]`; do anything you want here
      complete(HttpResponse())
    }
  }
}

b) Explicitly accessing RequestContext:

val route =  {
  path("example") { ctx =>
    ctx.request.headers // Returns `Seq[HttpHeader]`; do anything you want here
    ctx.complete(...)
  }
}

There’s also a whole family of directives related to headers, like headerValueByName or optionalHeaderValueByName. You can find the details here.

Attribution
Source : Link , Question Author : npmrtsv , Answer Author : Paweł Jurczenko

Leave a Comment