Search code examples
f#suave

Custom dynamic response with Suave?


I want to build a simple counter with Suave.

[<EntryPoint>]
let main argv =

  let mutable counter = 0;

  let app =
    choose
      [
        GET
        >=> choose
          [
            path "/" >=> OK "Hello, world. ";
            path "/count" >=> OK (string counter)
          ]
        POST
        >=> choose
          [
            path "/increment"
            >=> (fun context -> async {
              counter <- counter + 1
              return Some context
            })
          ]
      ]

  startWebServer defaultConfig app
  0

However, with my current solution, the count at /count never updates.

I think this is because the WebPart is computed when the app is launched, instead of for each request.

What is the best way to achieve this in Suave?


Solution

  • You are right in the assumption that Webparts are values, so computed once. (See this).

    You need to use a closure to get what you want:

    path "/count" >=> (fun ctx ->
        async {
            let c = counter in return! OK (string c) ctx
        })