Akka-http: How to get custom header from a request

2019-03-31 03:05发布

问题:

I send following headers in a request to my akka-http api: "Content-type": "application/json", "Accept": "application/json", "AppId": "some_id".

How do I get "AppId" custom header in my akka-http route?

(get & parameters("id")) { (id) =>
      complete {
        val appId = ?? // I want to get custom header here.
      }
    } 

Thanks.

回答1:

You need to use one of the HeaderDirectives (HeaderDirectives docs) to extract the header. For example, if it's a custom one you can use headerValueByName which yields the value of the header, and rejects the route if the header was not present (if the header is optional you can use optionalHeaderValueByName):

headerValueByName("AppId") { appId =>
  complete(s"The AppId was: $appId")
}

Happy hakking!



回答2:

I actually prefer creating custom directive for things like authentication tokens, app ids and other parameters that are sort of mandatory for serving client's request. In your case it might look like this

val extractAppId = (headerValueByName("AppId") | headerValueByName("AppId2")).tflatMap[Tuple1[String]] {
  case Tuple1(appId) =>
    if (!appId.equalsIgnoreCase("BannedAppId"))
      provide(appId)
    else
      complete(StatusCodes.Forbidden -> "Your application is banned")
}.recover {
  case rejections => reject(ValidationRejection("AppId is not provided"))
}

which is used like

extractAppId { appId =>
 get {
  complete {
   "Your AppId is " + appId
  }
 }
}

To make my example more interesting I added support of conditional response based on provided AppId.