# asynchttpserver

- Manual
- Standard library
- Index

Search:
Group by:

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 you should use a reverse proxy (for example nginx) instead of allowing users to connect directly to this server.

# Basic usage

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

    var server = newAsyncHttpServer()
    proc cb(req: Request) {.async.} =
      await req.respond(Http200, "Hello World")

    waitFor server.serve(Port(8080), cb)

# Imports

tables, 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.

  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, FutureError], 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, FutureError], 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 serve(server: AsyncHttpServer; port: Port;
              callback: proc (request: Request): Future[void] {...}{.closure, gcsafe.};
              address = ""): owned(Future[void]) {...}{.raises: [Exception, FutureError],
        tags: [RootEffect, WriteIOEffect, ReadIOEffect].}

  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.

  Source Edit

    proc close(server: AsyncHttpServer) {...}{.raises: [Exception, SslError, OSError],
                                       tags: [RootEffect].}

  Terminates the async http server instance. Source Edit

# Exports

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