Source Edit

This module implements a high performance asynchronous HTTP server.

This HTTP server has not been designed to be used in production, but for testing applications locally. Because of this, when deploying your application in production you should use a reverse proxy (for example nginx) instead of allowing users to connect directly to this server.

Example: cmd: -r:off

  1. import std/asynchttpserver
  2. # This example will create an HTTP server on an automatically chosen port.
  3. # It will respond to all requests with a `200 OK` response code and "Hello World"
  4. # as the response body.
  5. import std/asyncdispatch
  6. proc main {.async.} =
  7. var server = newAsyncHttpServer()
  8. proc cb(req: Request) {.async.} =
  9. echo (req.reqMethod, req.url, req.headers)
  10. let headers = {"Content-type": "text/plain; charset=utf-8"}
  11. await req.respond(Http200, "Hello World", headers.newHttpHeaders())
  12. server.listen(Port(0)) # or Port(8080) to hardcode the standard HTTP port.
  13. let port = server.getPort
  14. echo "test this with: curl localhost:" & $port.uint16 & "/"
  15. while true:
  16. if server.shouldAcceptRequest():
  17. await server.acceptRequest(cb)
  18. else:
  19. # too many concurrent connections, `maxFDs` exceeded
  20. # wait 500ms for FDs to be closed
  21. await sleepAsync(500)
  22. waitFor main()

Imports

asyncnet, asyncdispatch, parseutils, uri, strutils, httpcore, nativesockets, since

Types

  1. AsyncHttpServer = ref object
  2. ## The maximum content-length that will be read for the body.

Source Edit

  1. Request = object
  2. client*: AsyncSocket
  3. reqMethod*: HttpMethod
  4. headers*: HttpHeaders
  5. protocol*: tuple[orig: string, major, minor: int]
  6. url*: Uri
  7. hostname*: string ## The hostname of the client that made the request.
  8. body*: string

Source Edit

Consts

  1. nimMaxDescriptorsFallback {.intdefine.} = 16000

fallback value for when maxDescriptors is not available. This can be set on the command line during compilation via -d:nimMaxDescriptorsFallback=N Source Edit

Procs

  1. proc acceptRequest(server: AsyncHttpServer; callback: proc (request: Request): Future[
  2. void] {.closure, ...gcsafe.}): owned(Future[void]) {....stackTrace: false,
  3. raises: [Exception], tags: [RootEffect], forbids: [].}

Accepts a single request. Write an explicit loop around this proc so that errors can be handled properly. Source Edit

  1. proc close(server: AsyncHttpServer) {....raises: [LibraryError, Exception, SslError],
  2. tags: [RootEffect], forbids: [].}

Terminates the async http server instance. Source Edit

  1. proc getPort(self: AsyncHttpServer): Port {....raises: [OSError, Exception],
  2. tags: [], forbids: [].}

Returns the port self was bound to.

Useful for identifying what port self is bound to, if it was chosen automatically, for example via listen(Port(0)).

Example:

  1. from std/nativesockets import Port
  2. let server = newAsyncHttpServer()
  3. server.listen(Port(0))
  4. assert server.getPort.uint16 > 0
  5. server.close()

Source Edit

  1. proc listen(server: AsyncHttpServer; port: Port; address = ""; domain = AF_INET) {.
  2. ...raises: [OSError, ValueError], tags: [WriteIOEffect, ReadIOEffect],
  3. forbids: [].}

Listen to the given port and address. Source Edit

  1. proc newAsyncHttpServer(reuseAddr = true; reusePort = false; maxBody = 8388608): AsyncHttpServer {.
  2. ...raises: [], tags: [], forbids: [].}

Creates a new AsyncHttpServer instance. Source Edit

  1. proc respond(req: Request; code: HttpCode; content: string;
  2. headers: HttpHeaders = nil): Future[void] {....raises: [Exception],
  3. tags: [RootEffect], forbids: [].}

Responds to the request with the specified HttpCode, headers and content.

This procedure will not close the client socket.

Example:

  1. import std/json
  2. proc handler(req: Request) {.async.} =
  3. if req.url.path == "/hello-world":
  4. let msg = %* {"message": "Hello World"}
  5. let headers = newHttpHeaders([("Content-Type","application/json")])
  6. await req.respond(Http200, $msg, headers)
  7. else:
  8. await req.respond(Http404, "Not Found")

Source Edit

  1. proc sendHeaders(req: Request; headers: HttpHeaders): Future[void] {.
  2. ...raises: [Exception], tags: [RootEffect], forbids: [].}

Sends the specified headers to the requesting client. Source Edit

  1. proc serve(server: AsyncHttpServer; port: Port;
  2. callback: proc (request: Request): Future[void] {.closure, ...gcsafe.};
  3. address = ""; assumedDescriptorsPerRequest = -1; domain = AF_INET): owned(
  4. Future[void]) {....stackTrace: false, raises: [Exception], tags: [
  5. WriteIOEffect, ReadIOEffect, RootEffect, TimeEffect], forbids: [].}

Starts the process of listening for incoming HTTP connections on the specified address and port.

When a request is made by a client the specified callback will be called.

If assumedDescriptorsPerRequest is 0 or greater the server cares about the process’s maximum file descriptor limit. It then ensures that the process still has the resources for assumedDescriptorsPerRequest file descriptors before accepting a connection.

You should prefer to call acceptRequest instead with a custom server loop so that you’re in control over the error handling and logging.

Source Edit

  1. proc shouldAcceptRequest(server: AsyncHttpServer;
  2. assumedDescriptorsPerRequest = 5): bool {.inline,
  3. ...raises: [], tags: [], forbids: [].}

Returns true if the process’s current number of opened file descriptors is still within the maximum limit and so it’s reasonable to accept yet another request. Source Edit

Exports

Http417, Http503, Http431, HttpTrace, contains, Http304, Http406, $, HttpMethod, Http408, is4xx, is1xx, Http411, is3xx, Http207, Http418, Http206, HttpHead, HttpPost, clear, Http101, httpNewLine, Http505, Http413, Http423, Http409, hasKey, Http200, []=, Http414, add, Http401, Http511, Http205, \==, Http407, Http500, Http404, Http416, Http507, Http302, HttpHeaders, Http300, Http428, Http410, is2xx, Http202, Http502, headerLimit, HttpHeaderValues, Http425, contains, newHttpHeaders, $, [], Http510, newHttpHeaders, Http305, Http451, Http504, Http426, HttpConnect, \==, Http308, del, HttpPut, Http402, pairs, Http429, HttpVersion, HttpDelete, is5xx, Http421, HttpOptions, Http307, Http102, Http301, HttpPatch, Http201, Http203, getOrDefault, Http100, Http208, Http501, []=, len, Http506, Http400, Http403, HttpGet, Http508, Http415, toString, Http412, Http103, Http405, Http303, Http204, Http424, HttpCode, Http422, Http226, []