Module httpserver

This module implements a simple HTTP-Server.

Warning: This module will soon be deprecated in favour of the asyncdispatch module, you should use it instead.


import strutils, sockets, httpserver

var counter = 0
proc handleRequest(client: Socket, path, query: string): bool {.procvar.} =
  client.send("Hello for the $#th time." % $counter & wwwNL)
  return false # do not stop processing

run(handleRequest, Port(80))


parseutils, strutils, os, osproc, strtabs, streams, sockets, asyncio


Server = object of RootObj
  socket: Socket
  port: Port
  client*: Socket              ## the socket to write the file data to
  reqMethod*: string           ## Request method. GET or POST.
  path*, query*: string         ## path and query the client requested
  headers*: StringTableRef     ## headers with which the client made the request
  body*: string                ## only set with POST requests
  ip*: string                  ## ip address of the requesting client
contains the current server state
PAsyncHTTPServer = ref AsyncHTTPServer


wwwNL = "\x0D\x0A"


proc serveFile(client: Socket; filename: string) {.
    raises: [ValueError, OSError, Exception, IOError],
    tags: [WriteIOEffect, ReadIOEffect].}
serves a file to the client.
proc open(s: var Server; port = Port(80); reuseAddr = false) {.raises: [OSError],
    tags: [WriteIOEffect, ReadIOEffect].}
creates a new server at port port. If port == 0 a free port is acquired that can be accessed later by the port proc.
proc port(s: var Server): Port {.raises: [], tags: [].}
get the port number the server has acquired.
proc next(s: var Server) {.raises: [OSError, TimeoutError, ValueError, KeyError,
                       tags: [ReadIOEffect, TimeEffect, WriteIOEffect].}
proceed to the first/next request.
proc close(s: Server) {.raises: [], tags: [].}
closes the server (and the socket the server uses).
proc run(handleRequest: proc (client: Socket; path, query: string): bool {.closure.};
        port = Port(80)) {.raises: [OSError, TimeoutError, ValueError, KeyError,
                        tags: [WriteIOEffect, ReadIOEffect, TimeEffect].}
encapsulates the server object and main loop
proc asyncHTTPServer(handleRequest: proc (server: PAsyncHTTPServer; client: Socket;
                                       path, query: string): bool {.closure, gcsafe.};
                    port = Port(80); address = ""; reuseAddr = false): PAsyncHTTPServer {.
    raises: [OSError], tags: [WriteIOEffect, ReadIOEffect].}
Creates an Asynchronous HTTP server at port.
proc register(d: Dispatcher; s: PAsyncHTTPServer) {.raises: [], tags: [].}
Registers a PAsyncHTTPServer with a Dispatcher.
proc close(h: PAsyncHTTPServer) {.raises: [], tags: [].}
Closes the PAsyncHTTPServer.

© 2006–2017 Andreas Rumpf
Licensed under the MIT License.