2016-06-30 49 views
4

我有形式簡單Suave.io服務器最簡單的方法:什麼是檢查傳入的請求中包含一定的標頭值

let Ok o = o |> JsonConvert.SerializeObject |> Successful.OK 
let NotOk o = o |> JsonConvert.SerializeObject |> RequestErrors.BAD_REQUEST 

type Result<'T> = 
| Success of 'T 
| Failure of string 

let DoThing someParam anotherParam = 
    let stats = Success(999) // <- business code here 
    match stats with 
    | Success s -> s |> Ok 
    | Failure m -> m |> NotOk 
... 
     let app = 
      choose 
       [ GET >=> choose 
        [ 
         pathScan "/someroute/%i/%i" (fun (p1, p2) -> 
           DoThing p1 p2) 
        ] 
       ] 
     startWebServer config app 
     0 

我想檢查請求包含一個頭一個特定的名稱和值,並且當NotOk缺失或不正確時返回NotOk。達到此目的最簡單的方法是什麼?

我是Suave.io的作曲風格的新人。

+0

你可以看看:http://stackoverflow.com/questions/31672110/suave-io-using-pathscan-and-request-together。我認爲你可以檢查這個請求。注意:'type WebPart = HttpContext - > Async '和'type HttpContext = {request:HttpRequest;響應:HttpResponse}'。所以你需要打開'WebPart'。 – halcwb

回答

3

我認爲這會做你需要的東西:

#r "Newtonsoft.Json.dll" 
#r "Suave.dll" 
#r "Suave.Testing.dll" 
#r "System.Net.Http.dll" 
#r "Fuchu.dll" 

open System.Net 
open System.Net.Http 

open Suave 
open Suave.Operators 
open Newtonsoft.Json 
open Suave.Filters 
open Suave.Testing 

let Ok o = o |> JsonConvert.SerializeObject |> Successful.OK 
let NotOk o = o |> JsonConvert.SerializeObject |> RequestErrors.BAD_REQUEST 

type Result<'T> = 
| Success of 'T 
| Failure of string 

let DoThing someParam anotherParam = 
    let stats = Success(999) // <- business code here 
    match stats with 
    | Success s -> s |> Ok 
    | Failure m -> m |> NotOk 

let checkHeader ctx = 
    asyncOption { 
     match "key" |> ctx.request.header with 
     | Choice1Of2 k1 -> 
      printfn "Header k1: %s" k1 
      return ctx 
     | Choice2Of2 k2 -> 
      printfn "Header k2: %s" k2 
      return { ctx with 
         response = { ctx.response with 
             status = HTTP_400 } } } 

let app = 
    choose 
     [ GET >=> choose 
      [ 
       pathScan "/someroute/%i/%i" (fun (p1, p2) -> 
         DoThing p1 p2) 
       >=> checkHeader 
      ] 
     ] 

let emptyCont = new ByteArrayContent([||]) |> Some 

runWith defaultConfig app 
|> reqResp HttpMethod.GET 
      "/someroute/1/2" "" 
      None 
      None 
      DecompressionMethods.None 
      id 
      id 

請確保您有在同一個目錄所需的庫作爲這個腳本,你可以運行它。由於沒有key標頭,因此結果將爲BAD_REQUEST,其內容爲999.

checkHeader會執行此操作。

+0

謝謝你這麼多! – Kit

相關問題