Spray IO, add header to response

3.5k views Asked by At

I have (formerly) REST spray.io webservice. Now, I need to generate SESSIONID in one of my methods to be used with some other methods. And I want it to be in the response header.

Basically, I imagine logic like the following:

 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
       }
     } 
   }
 }

But, it doesn't work inside complete, I mean respondWithHeader directive. I need an advice.

1

There are 1 answers

5
yǝsʞǝla On BEST ANSWER

There is a respondWithHeader directive in Spray. Here is official doc and example of how you could use it:

 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))
             }
           }
       }
   }
 }