asynchttpserver

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

This example will create an HTTP server on port 8080. The server will respond to all requests with a 200 OK response code and "Hello World" as the response body.

import asynchttpserver, asyncdispatch

proc main {.async.} =
  var server = newAsyncHttpServer()
  proc cb(req: Request) {.async.} =
    let headers = {"Date": "Tue, 29 Apr 2014 23:40:08 GMT",
        "Content-type": "text/plain; charset=utf-8"}
    await req.respond(Http200, "Hello World", headers.newHttpHeaders())
  
  server.listen Port(8080)
  while true:
    if server.shouldAcceptRequest():
      await server.acceptRequest(cb)
    else:
      poll()

asyncCheck main()
runForever()

Imports

asyncnet, asyncdispatch, parseutils, uri, strutils, httpcore

Types

Request = object
  client*: AsyncSocket
  reqMethod*: HttpMethod
  headers*: HttpHeaders
  protocol*: tuple[orig: string, major, minor: int]
  url*: Uri
  hostname*: string          ## The hostname of the client that made the request.
  body*: string
Source Edit
AsyncHttpServer = ref object
  socket: AsyncSocket
  reuseAddr: bool
  reusePort: bool
  maxBody: int               ## The maximum content-length that will be read for the body.
  maxFDs: int
Source Edit

Consts

nimMaxDescriptorsFallback = 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

proc newAsyncHttpServer(reuseAddr = true; reusePort = false; maxBody = 8388608): AsyncHttpServer {...}{.
    raises: [], tags: [].}
Creates a new AsyncHttpServer instance. Source Edit
proc sendHeaders(req: Request; headers: HttpHeaders): Future[void] {...}{.
    raises: [Exception], tags: [RootEffect].}
Sends the specified headers to the requesting client. Source Edit
proc respond(req: Request; code: HttpCode; content: string;
             headers: HttpHeaders = nil): Future[void] {...}{.raises: [Exception],
    tags: [RootEffect].}

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

This procedure will not close the client socket.

Example:

import json
proc handler(req: Request) {.async.} =
  if req.url.path == "/hello-world":
    let msg = %* {"message": "Hello World"}
    let headers = newHttpHeaders([("Content-Type","application/json")])
    await req.respond(Http200, $msg, headers)
  else:
    await req.respond(Http404, "Not Found")
Source Edit
proc listen(server: AsyncHttpServer; port: Port; address = "") {...}{.
    raises: [OSError, Exception, ValueError],
    tags: [RootEffect, WriteIOEffect, ReadIOEffect].}
Listen to the given port and address. Source Edit
proc shouldAcceptRequest(server: AsyncHttpServer;
                         assumedDescriptorsPerRequest = 5): bool {...}{.inline,
    raises: [], tags: [].}
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
proc acceptRequest(server: AsyncHttpServer; callback: proc (request: Request): Future[
    void] {...}{.closure, gcsafe.}): owned(Future[void]) {...}{.raises: [Exception],
    tags: [RootEffect].}
Accepts a single request. Write an explicit loop around this proc so that errors can be handled properly. Source Edit
proc serve(server: AsyncHttpServer; port: Port;
           callback: proc (request: Request): Future[void] {...}{.closure, gcsafe.};
           address = ""; assumedDescriptorsPerRequest = -1): owned(Future[void]) {...}{.
    raises: [Exception],
    tags: [RootEffect, WriteIOEffect, ReadIOEffect, TimeEffect].}

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
proc close(server: AsyncHttpServer) {...}{.raises: [Exception, LibraryError, SslError],
                                      tags: [RootEffect].}
Terminates the async http server instance. Source Edit

Exports

Http417, Http503, Http431, ==, contains, Http304, Http406, ==, $, clear, Http408, $, Http411, is3xx, Http418, Http206, HttpMethod, Http101, httpNewLine, Http505, Http413, newHttpHeaders, Http200, []=, Http414, add, Http401, Http205, ==, Http407, Http500, Http404, Http416, Http308, Http302, HttpHeaders, Http300, Http428, Http410, is2xx, Http202, Http502, headerLimit, HttpHeaderValues, contains, newHttpHeaders, $, [], Http305, Http451, Http409, Http504, Http426, hasKey, del, pairs, Http429, HttpVersion, []=, Http421, Http307, Http301, is4xx, Http203, getOrDefault, Http100, Http501, len, Http400, Http403, is5xx, Http415, toString, Http412, Http405, Http303, Http204, Http201, HttpCode, Http422, []

© 2006–2021 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/asynchttpserver.html