This isn't cross platform, (not windows, not android), but on osx,bsd,linux 
there's an easy way to set up an asyncEvent to trigger on a signal. 
(undocumented but exported from asyncdispatch)
    
    
    import asynchttpserver, asyncdispatch
    import system/ansi_c #SIGINT is defined elsewhere, i.e. posix, maybe that's 
a better include idk i was just hoping for some sort of cross platformitude
    
    proc main() =
      let server = newAsyncHttpServer()
      
      # let dbConn = await connect2db()
      addSignal(SIGINT,proc(fd:AsyncFD):bool =
        echo "Server Shutdown on SIGINT"
        server.close()
        quit(0)
      )
      proc cb(req: Request) {.async.} =
        await req.respond(Http200, "Hello World")
      
      try:
        waitFor server.serve(Port(8080), cb)
      except:
        let e = getCurrentException
        let m = if e.isNil: "None" else: e.msg
        echo "Start the server shutdown ...",m
      finally:
        # await dbConn.close()
        server.close()
        echo "Server shutdown completed."
        quit(QuitSuccess)
    
    main()
    
    
    Run

Reply via email to