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

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!