I'm exploring WebSockets and async/await. But I'm finding that the most trivial example of an async HTTP server crashes on every request. If I run an exact copy of the example from the asynchttpserver documentation:
import asynchttpserver, asyncdispatch
var server = newAsyncHttpServer()
proc cb(req: Request) {.async.} =
await req.respond(Http200, "Hello World")
waitFor server.serve(Port(8080), cb)
... it will crash hard when I send an HTTP GET to it, from any client I've tried (Safari, curl, httpie):
/Users/snej/Code/nim/blip/src/server.nim(7) server
/usr/local/Cellar/nim/1.2.0/nim/lib/pure/asyncdispatch.nim(1886) waitFor
/usr/local/Cellar/nim/1.2.0/nim/lib/pure/asyncdispatch.nim(1576) poll
/usr/local/Cellar/nim/1.2.0/nim/lib/pure/asyncdispatch.nim(1340) runOnce
/usr/local/Cellar/nim/1.2.0/nim/lib/pure/asyncdispatch.nim(210) processPendingCallbacks
/usr/local/Cellar/nim/1.2.0/nim/lib/pure/asyncmacro.nim(37) processRequestNimAsyncContinue
/usr/local/Cellar/nim/1.2.0/nim/lib/pure/asynchttpserver.nim(258) processRequestIter
/usr/local/Cellar/nim/1.2.0/nim/lib/pure/asyncmacro.nim(319) cb
/usr/local/Cellar/nim/1.2.0/nim/lib/pure/asyncmacro.nim(34) cbNimAsyncContinue
/Users/snej/Code/nim/blip/src/server.nim(5) cbIter
/usr/local/Cellar/nim/1.2.0/nim/lib/pure/asynchttpserver.nim(103) respond
/usr/local/Cellar/nim/1.2.0/nim/lib/pure/httpcore.nim(180) hasKey
SIGSEGV: Illegal storage access. (Attempt to read from nil?)
I don't know this code at all, but from quick inspection I can see that the respond function in asynchttpserver.nim has a headers parameter that defaults to nil, but it calls headers.hasKey("Content-Length") without checking for nil first. Oops.
Is this module generally considered solid, and this is just an unusual bug where no one ever tested the examples in the docs? Or is there another module I should use instead?
—Jens
I confirmed that if I change line 5 to
await req.respond(Http200, "Hello World", newHttpHeaders())
(passing in a non-nil headers object), the program works fine.
I guess this has turned into a bug report, although when I started this post I didn't know what the problem was. Thanks for the rubber-duckie debugging, forum! What Github repo should I file this under? Nim itself?