This module implements a simple HTTP-Server.
Example:
import strutils, sockets, httpserver var counter = 0 proc handleRequest(client: TSocket, path, query: string): bool {.procvar.} = inc(counter) client.send("Hello for the $#th time." % $counter & wwwNL) return false # do not stop processing run(handleRequest, TPort(80))
Warning: The API of this module is unstable, and therefore is subject to change.
Types
TServer = object of TObject socket: TSocket port: TPort client*: TSocket ## 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*: PStringTable ## 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 TAsyncHTTPServer
Consts
wwwNL = "\x0D\x0A"
Procs
proc serveFile(client: TSocket; filename: string) {. raises: [EOutOfMemory, EInvalidValue, EOS, E_Base], tags: [FWriteIO, FReadIO].}
- serves a file to the client.
proc open(s: var TServer; port = TPort(80); reuseAddr = false) {.raises: [EOS], tags: [FWriteIO, FReadIO].}
- 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 TServer): TPort {.raises: [], tags: [].}
- get the port number the server has acquired.
proc next(s: var TServer) {.raises: [EOS, ETimeout, EInvalidValue, EOverflow], tags: [FReadIO, FTime, FWriteIO].}
- proceed to the first/next request.
proc close(s: TServer) {.raises: [], tags: [].}
- closes the server (and the socket the server uses).
proc run(handleRequest: proc (client: TSocket; path, query: string): bool {. closure.}; port = TPort(80)) {.raises: [EOS, ETimeout, EInvalidValue, EOverflow], tags: [FWriteIO, FReadIO, FTime].}
- encapsulates the server object and main loop
proc asyncHTTPServer(handleRequest: proc (server: PAsyncHTTPServer; client: TSocket; path, query: string): bool {.closure.}; port = TPort(80); address = ""; reuseAddr = false): PAsyncHTTPServer {. raises: [EOS], tags: [FWriteIO, FReadIO].}
- Creates an Asynchronous HTTP server at port.
proc register(d: PDispatcher; s: PAsyncHTTPServer) {.raises: [], tags: [].}
- Registers a PAsyncHTTPServer with a PDispatcher.
proc close(h: PAsyncHTTPServer) {.raises: [], tags: [].}
- Closes the PAsyncHTTPServer.