【问题标题】:Spray IO, add header to response喷IO,给响应加header
【发布时间】:2014-09-19 09:11:36
【问题描述】:

我(以前)有 REST spray.io 网络服务。现在,我需要在我的一种方法中生成 SESSIONID 以与其他方法一起使用。我希望它出现在响应标头中。

基本上,我想象的逻辑如下:

 path("/...") {
   get {
     complete {
       // some logic here
       // .....
       someResult match {
         case Some(something) =>
           val sessionID = generateSessionID
           session(sessionID) = attachSomeData(something)
           // here I need help how to do my imaginary respond with header
           [ respond-with-header ? ]("X-My-SessionId", sessionID) {
             someDataMarshalledToJSON(something)
           }


         case None => throw .... // wrapped using error handler
       }
     } 
   }
 }

但是,它在内部不起作用,我的意思是 respondWithHeader 指令。我需要一个建议。

【问题讨论】:

    标签: scala spray spray-dsl


    【解决方案1】:

    Spray 中有一个respondWithHeader 指令。这是官方doc 以及如何使用它的示例:

     def respondWithSessionId(sessionID: String) =
       respondWithHeader(RawHeader("X-My-SessionId", sessionID))
    
     path("/...") {
       get {
           // some logic here
           // .....
           sessionIDProvider { sessionID =>
               respondWithMediaType(`application/json`) { // optionally add this if you want
                 respondWithSessionId(sessionID) {
                   complete(someDataMarshalledToJSON(something))
                 }
               }
           }
       }
     }
    

    【讨论】:

    • 他们说完整之外的代码将在路由构建时进行评估,这不会带来不良影响吗?我还有一些validate()params() 指令目前在complete 之前。
    • 是的,没错,我只是懒得把所有东西都移到complete。只需使用以下指令包装内容:params { validate { ... } }。我更喜欢将所有这些变量排除在路由之外,而是调用一些函数来保持路由非常简单明了。
    • 谢谢,我为我的特殊情况找到了更简单的解决方案:provide(generateSessionId) { sessionId => respondWithHeader(.., sessionId) { complete and the rest unchanged, can use sessionId inside } }
    • 你能用正确的解决方案更新答案吗?我需要自己添加一个 Raw/Custom 标头,但我对如何做有点困惑。
    • @djsumdog 只需使用respondWithHeader(RawHeader("your_header_name", header_value)) { ... your code that completes the route ... },如答案所示。例如:respondWithHeader(RawHeader("MYHEADER", "123")) { complete("test") }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    相关资源
    最近更新 更多