Context in Idris

Here’s the translation of the Go code to Idris, formatted in Markdown suitable for Hugo:

Our example demonstrates how to create a simple HTTP server and handle contexts for cancellation. In Idris, we can achieve similar functionality using the Network.HTTP and Control.ST modules.

import Network.HTTP
import Control.ST
import Data.IORef
import System.Concurrency

hello : IORef Int -> (req : Request) -> (res : Response) -> IO ()
hello counter req res = do
    putStrLn "server: hello handler started"
    count <- readIORef counter
    writeIORef counter (count + 1)
    
    -- Simulate some work
    fork $ do
        threadDelay 10000000  -- 10 seconds
        putStrLn "Work completed"
        setStatus res 200
        setBody res "hello\n"
        end res
    
    putStrLn "server: hello handler ended"

main : IO ()
main = do
    counter <- newIORef 0
    let handler = hello counter
    serve 8090 handler

In this Idris version:

  1. We import necessary modules for HTTP handling, state management, and concurrency.

  2. The hello function takes an IORef Int to keep track of request count, along with the request and response objects.

  3. We simulate work by forking a thread that waits for 10 seconds before sending a response. This is similar to the select statement in the original example.

  4. The main function sets up the server to listen on port 8090.

  5. We use IORef to maintain a counter across requests, demonstrating stateful operations.

  6. Instead of using a context.Context, we rely on Idris’s built-in concurrency primitives. The fork function is used to start a new thread for the simulated work.

To run the server:

$ idris -p contrib -p network server.idr -o server
$ ./server

To test the server, you can use curl in another terminal:

$ curl localhost:8090/hello

Note that Idris’s HTTP server implementation might differ from Go’s, and some features like explicit context cancellation are not directly available. However, this example demonstrates how to create a basic HTTP server with similar functionality in Idris.