Context in Nim

Here’s the translation of the Go code to Nim, along with explanations in Markdown format suitable for Hugo:

In the previous example we looked at setting up a simple HTTP server. HTTP servers are useful for demonstrating the usage of asyncdispatch for controlling cancellation. The asyncdispatch module in Nim provides utilities for asynchronous programming and cancellation.

import asynchttpserver, asyncdispatch
import times

proc hello(req: Request): Future[void] {.async.} =
  echo "server: hello handler started"
  defer: echo "server: hello handler ended"

  try:
    await sleepAsync(10000)  # Simulate work for 10 seconds
    await req.respond(Http200, "hello\n")
  except CancelledError:
    echo "server: ", getCurrentExceptionMsg()
    await req.respond(Http500, getCurrentExceptionMsg())

proc main() {.async.} =
  var server = newAsyncHttpServer()
  proc handler(req: Request) {.async.} =
    if req.url.path == "/hello":
      await hello(req)
    else:
      await req.respond(Http404, "Not found")

  server.listen(Port(8090))
  while true:
    if server.shouldAcceptRequest():
      await server.acceptRequest(handler)
    else:
      await sleepAsync(500)

waitFor main()

In this Nim version, we use the asynchttpserver and asyncdispatch modules to create an asynchronous HTTP server. The hello procedure is defined as an asynchronous function that simulates work for 10 seconds before responding.

The main procedure sets up the server and defines a handler that routes requests to the hello procedure when the path is “/hello”.

To run the server:

$ nim c -r context.nim

Simulate a client request to /hello, hitting Ctrl+C shortly after starting to signal cancellation:

$ curl localhost:8090/hello
server: hello handler started
^C
server: Cancelled
server: hello handler ended

In this Nim version, we use asyncdispatch for asynchronous programming, which is similar to Go’s concurrency model. The CancelledError exception is used to handle cancellation, which is analogous to the context cancellation in Go.

The structure and functionality of the original Go example are maintained, but adapted to Nim’s syntax and idioms. The concept of context is replaced with Nim’s asynchronous programming model, which provides similar capabilities for handling cancellation and timeouts.