2013-04-01 13 views
2

對於POST和PUT請求我使用的語法如下:我應該如何使用不同的狀態代碼來響應Spray中的GET請求?

put { 
    entity(as[CaseClass]) { entity => 
    returnsOption(entity).map(result => complete{(Created, result)}) 
     .getOrElse(complete{(NotFound, "I couldn't find the parent resource you're modifying")}) 
    } 
} 

現在GET請求我試圖做同樣的,但我不能得到它的工作類似我PUT解決方案。用GET請求做這件事的好方法是什麼?

更新: 我有了這個與下面的技巧工作:

(get & parameters('ignored.?)) { 
    //TODO find a way to do this without ignored parameters 
    (ingored:Option[String]) => { 
    returnsOption().map(result => complete(result)) 
     .getOrElse(complete{(NotFound, "")}) 
    } 
} 

我期望類似有可能與() =>ctx =>的東西,但是,這並不靠譜,因爲它給了麻煩與編組:

... could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[(spray.http.StatusCodes.ClientError, String)] 
    }).getOrElse(ctx.complete{(NotFound, "")}) 
          ^

難道這是不知何故與我使用spray-json的事實?

回答

4

此代碼應工作:

get { 
    ctx => 
    ctx.complete(returnsOption()) 
} 

如果一開始不使用ctx =>,你的代碼可能只在路徑構建時執行。

在這裏你可以找到一些解釋:Understanding the DSL Structure

+0

這樣的工作,但我想返回一個不同的StatusCode根據更多的選項定義。如果您將選項映射到完成,則只會在啓動時執行一次,這不是我的意圖。 – iwein

+0

這就是爲什麼你應該閱讀關於該主題的上述文檔。重要的是要明白,只有以'ctx =>'開頭的塊內部的代碼才能保證在每個請求上執行,並且其他代碼可能僅在執行期間執行(有時可能在請求處理時間但不一定)路線_building_時間。 – jrudolph

+0

@jrudolph我明白,我會編輯問題以反映該部分。現在,如果代碼將根據選項的內容返回不同的狀態代碼,它將完全回答問題。 – iwein

15

使用HttpResponse這樣例如

complete{ 
    HttpResponse(StatusCodes.OK, HttpBody(ContentType(`text/html`), "test test: " + System.currentTimeMillis.toString)) 
} 

更新:我一直在使用噴有一段時間了。原來有更好的辦法:

complete { 
    StatusCodes.BandwidthLimitExceeded -> MyCustomObject("blah blah") 
} 
+0

有沒有更簡潔的寫法呢? – Phil

+1

@Phil謝謝你提醒我這個問題。是的,有更好的辦法。我更新了答案。 – expert

相關問題