Module asynchttpserver

This module implements a high performance asynchronous HTTP server.

Examples

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)

Types

RequestBody* = ref object
  s: AsyncStream
  length: int64
  data: string
  cachedStream: AsyncStream
The request body implemented as asynchronous stream   Source Edit
Request* = object
  client*: AsyncSocket
  reqMethod*: string
  headers*: HttpHeaders
  protocol*: tuple[orig: string, major, minor: int]
  url*: Uri
  hostname*: string
  reqBody*: RequestBody
The hostname of the client that made the request.   Source Edit
AsyncHttpServer* = ref object
  socket: AsyncSocket
  reuseAddr: bool
  reusePort: bool
  Source Edit

Procs

proc newAsyncHttpServer*(reuseAddr = true; reusePort = false): AsyncHttpServer
Creates a new AsyncHttpServer instance.   Source Edit
proc len*(body: RequestBody): int64
Returns the length of the body   Source Edit
proc getStream*(body: RequestBody): AsyncStream
Returns the request's body as asynchronous stream   Source Edit
proc body*(request: Request): Future[string] {.
async
.}
Returns the body of the request as the string.   Source Edit
proc sendHeaders*(req: Request; headers: HttpHeaders): Future[void]
Sends the specified headers to the requesting client.   Source Edit
proc respond*(req: Request; code: HttpCode; content: string; headers: HttpHeaders = nil): Future[
    void]

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

This procedure will not close the client socket.

  Source Edit
proc serve*(server: AsyncHttpServer; port: Port;
           callback: proc (request: Request): Future[void] {.
closure, gcsafe
.}; address = "") {.
async
.}

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)
Terminates the async http server instance.   Source Edit