簡體   English   中英

F#長頸鹿:基於結果的不同緩存頭

[英]F# Giraffe: Different cache headers based on result

我正在努力根據結果是確定還是錯誤來設置不同的緩存響應標頭。 我的代碼類似於以下內容(但結果中包含其他類型):

let resultToJson (result:Result<'a,string>) : HttpHandler = 
    match result with
    | Ok o -> Successful.ok (json o)
    | Error s -> ServerErrors.internalError (text s)

我可以通過執行以下操作來添加標題:

let resultToJson (result:Result<'a,string>) : HttpHandler = 
    fun (next : HttpFunc) (ctx : HttpContext) ->
        let response =
            let headers = ctx.Response.Headers
            match result with
            | Ok o ->
                headers.Add("Cache-Control", new StringValues("public, max-age=10, stale-while-revalidate=2"))
                headers.Add("Vary", new StringValues("Origin"))
                Successful.ok (json o)
            | Error s -> 
                headers.Add("Cache-Control", new StringValues("no-cache"))
                ServerErrors.internalError (text s)
        response next ctx

但這感覺不對。 我想使用ResponseCaching模塊中的標准HttpHandlers來設置正確的緩存頭:

publicResponseCaching 10 (Some "Origin") // For Ok: Add 10 sec public cache, Vary by Origin
noResponseCaching // For Error: no caching

我該如何實現?

應該將響應緩存處理程序通過管道傳遞到普通管道中。 在“ Ok和“ Error之間進行選擇是一個選擇函數,因此您可以使用一個選擇,該選擇采用可以嘗試的處理程序列表。 要拒絕路徑,只需返回一個task { return None } ,然后向前移動,即next ctx

如果您想像現在一樣將所有邏輯保留在一個控制器中,只需保持匹配並將JSON /文本響應通過管道傳遞到一個緩存處理程序中即可。

let fn = json o >=> publicResponseCaching 30 None) in fn next ctx

如果它嵌套在處理程序內部,而不是在管道中,則必須應用nextctx

我找到了解決我問題的方法。

是的,我可以使用fish運算符( >=> )鏈接Gerard和Honza Brestan所述的HttpHandlers。 我之所以無法進行這項工作,是因為我還在打開的模塊中為Result類型創建了一個fish運算符。 基本上我創造了合適的魚湯

一旦我重構了代碼,以致包含Result fish運算符的模塊不在此范圍內打開,則一切正常。

要記住的另一點是,在完成HttpHandler 之前需要調用響應緩存,否則將不調用它:

// Simplified code
let resultToJson =
    function
    | Ok o -> publicResponseCaching 10 (Some "Origin") >=> Successful.ok(json o)
    | Error e -> noResponseCaching >=> ServerErrors.internalError(text e)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM