libstd/http

An HTTP/1.1 server: routes that map a path to a TryC function, static files read from a base directory, custom error pages, middleware, cookies, sessions shared by all workers, keep-alive and pipelining. On Linux a supervisor process starts one worker per setNumCoworker, each serving many connections at once with epoll on non-blocking sockets, and replaces any worker that crashes. A bad request, a client that disappears or a slow client costs at most its own connection, never a worker. The server that serves this documentation is written with it (esempio/server.tryc).

#include <libstd/http>

Includes libstd/mem, libstd/random, libstd/cpuinfo, libstd/net, libstd/stdio, libstd/string, libstd/file, libstd/dict, libstd/list, libstd/process, libstd/sync, libstd/type, libstd/time. Cookies and sessions are two parts of it, with their own pages: libstd/http/cookies and libstd/http/session.

Example

#include <libstd/http>
#include <libstd/cpuinfo>

def home(self: HttpServer, req: HttpRequest) -> str:
    return self.page(req, "index.html")

def hello(self: HttpServer, req: HttpRequest) -> str:
    req.content_type = "text/plain"
    return "hello " + req.getQuery() + "\n"

def log_requests(self: HttpServer, req: HttpRequest) -> HttpRequest:
    if req.phase == HTTP_PHASE_AFTER:
        print(req.getAction() + " " + req.getPath() + " -> " + itoa(req.status) + "\n")
    return req

server = HttpServer(127, 0, 0, 1, 8000)
server.setBaseDir("./templates")
server.addMapsFunction("/", home)
server.addMapsFunction("/hello", hello)
server.addMapFile("/favicon.ico", "img/favicon.ico")
server.addMapCss("/style.css", "css/style.css")
server.setErrorPage(404, "404.html")
server.addMiddleWare("log", log_requests)

server.setNumCoworker(logical_cpu_count() as long)
server.run()

Routes and responses

A route maps an exact path to a function &(HttpServer, HttpRequest) -> str, passed by name to addMapsFunction. The string it returns is the response body. The response starts as 200 with Content-Type: text/html; charset=utf-8; the function changes either by setting req.status or req.content_type before it returns:

def new_item(self: HttpServer, req: HttpRequest) -> str:
    if req.getAction() != "POST":
        req.status = 405
        return "use POST\n"
    req.status = 201
    req.content_type = "text/plain"
    return "stored " + itoa(strlen(req.body)) + " bytes\n"

The request is in the HttpRequest: getAction() (the method, GET, POST, ...), getPath(), getQuery(), getVersion(), getHeader(name) (any case, "" if absent), req.cookies (see Cookies below), and req.body, the request body (its length is the request's Content-Length).

Site files and error pages

setBaseDir(dir) sets the directory that holds the site's files, like BASE_DIR in Django. Every relative file name given to addMapCss, addMapJs, addMapFile, setErrorPage and page is looked up inside it; an absolute one (/srv/site/a.css, C:\site\a.css) is used as it is, as with Python's os.path.join. Without a base directory, relative names start from the working directory of the process. The path is built at every request, so setBaseDir can come before or after the other calls.

As in Django, pages and static files can live in two directories of their own, both relative to the base directory: setBaseDirTemplate(dir) for the names given to page and setErrorPage (Django's template directory), setBaseDirStatic(dir) for the files of addMapCss, addMapJs and addMapFile (Django's STATIC_ROOT). Each setter stores the directory as given; getBaseDirTemplate() and getBaseDirStatic() return it joined to the base directory, so the order of the calls does not matter here either. Left unset, both are the base directory itself.

run() checks the three directories before it binds the port (is_dir from libstd/file): one that does not exist, or is a file, prints http: setBaseDirStatic: site/statik non e' una cartella and exits with 1. A typo, or a server started from the wrong working directory, shows up at start instead of as a 404 on every request. The check runs once the configuration is complete, so the order of the calls still does not matter. It does not look at the single files: a file registered with addMapFile and then moved still gets a 404.

server.setBaseDir("/srv/site")
server.setBaseDirTemplate("templates")    // /srv/site/templates
server.setBaseDirStatic("static")         // /srv/site/static
server.addMapFile("/img/logo.svg", "img/logo.svg")
server.setErrorPage(404, "errors/404.html")
server.setErrorPage(403, "errors/403.html")

def admin(self: HttpServer, req: HttpRequest) -> str:
    if not req.sessionHas("admin"):
        req.status = 403
        return ""
    return self.page(req, "admin.html")

Cookies

Every request has a Cookies object in req.cookies. get(name) and has(name) read the cookies the browser sent. set(name, value, max_age, flags) and remove(name) add Set-Cookie headers to the response, with HttpOnly and SameSite=Lax unless the flags say otherwise. Routes and middleware, in both phases, use them the same way. Lifetimes, flags, validation and examples are in libstd/http/cookies.

Response headers

req.setResponseHeader(name, value) adds a header to one response, from a route or a middleware in either phase. A second call with the same name, in any case, replaces the first. req.hasResponseHeader(name) tells whether the response already has one. server.setDefaultHeader(name, value) adds a header to every response of the server. Call it before run(). Its lines are written once, when it is called, and copied into each response as they are, so a default header costs nothing per request. A route that sets the same name with setResponseHeader replaces the default for its own response. hasResponseHeader does not see the defaults.

def report(self: HttpServer, req: HttpRequest) -> str:
    req.setResponseHeader("Cache-Control", "no-store")
    return self.page(req, "report.html")

server.setDefaultHeader("X-Content-Type-Options", "nosniff")

Both return 1 when the header is added, or 0 when they refuse it. They refuse:

The error responses the server sends without a route (400, 408, 413, 431, 501) carry no added headers.

libstd/http/security turns on the browser security headers with one call before run():

#include <libstd/http>
#include <libstd/http/security>

http_security_headers(server)
HeaderValueEffect
X-Content-Type-OptionsnosniffThe browser uses the Content-Type it receives instead of guessing it from the content.
X-Frame-OptionsDENYNo site can show the pages in a frame (clickjacking). For old browsers.
Content-Security-Policyframe-ancestors 'none'The same, for current browsers. A CSP in a <meta http-equiv> tag cannot contain frame-ancestors; it applies together with this one.
Referrer-Policystrict-origin-when-cross-originOther sites get only the domain of the page that links them, not its path.
Permissions-Policycamera=(), microphone=(), geolocation=()Turns off the camera, the microphone and geolocation.

A route that sends its own Content-Security-Policy replaces the default one, so it must include frame-ancestors itself. Strict-Transport-Security is not set: it only means something over HTTPS, which ends at the reverse proxy, so it belongs there. These headers are server defaults, not a middleware: in a one-worker test, a middleware that added the same five headers to every response cut throughput by 20-37%, while the defaults cost about 2%.

Middleware

A middleware is a function &(HttpServer, HttpRequest) -> HttpRequest registered with a name. Every request goes through each middleware twice:

  1. req.phase == HTTP_PHASE_BEFORE: before the route, in the order the middleware were added. It can read and change the request (for example rewrite req.path).
  2. req.phase == HTTP_PHASE_AFTER: after the route, in the opposite order. req.status, req.content_type and req.response_body already hold the response and can still be changed (add a footer, replace an error page, log the status).

It returns the request it was given, or another one. delMiddleWare(name) removes it.

Sessions

A session keeps data on the server for one browser, across requests; the browser only holds a random id in the sid cookie, and the data lives in one table shared by all the workers. Turn sessions on before run(), then use them from any route or middleware through the request:

def profile(self: HttpServer, req: HttpRequest) -> str:
    if not req.sessionHas("user"):
        req.status = 401
        return "log in first\n"
    return "hello " + req.sessionGet("user") + "\n"

server.enableSessions(1000 as long)

libstd/http/session explains how sessions are created, saved and expire, and what happens when a worker dies. It also has complete examples: login and logout, a protected section, a shopping cart, CSRF tokens and messages shown once.

Workers and the supervisor

run() binds the address, starts ncoworker worker processes (at least one) with fork, and never returns. The process that called it becomes the supervisor: it serves no request, it waits for its workers.

Why processes and not threads

The arena allocator behind new, string + and readfile is global and not thread-safe (see libstd/thread): a thread may not allocate. Every request allocates strings, so the workers are processes, each with its own arena. Routes and middleware run inside a worker and can allocate freely.

Connections and timeouts

An HTTP/1.1 connection stays open after a response (keep-alive) unless the client sends Connection: close; an HTTP/1.0 one only with Connection: keep-alive. A client can also send several requests at once (pipelining): they are answered in order, the next one when the previous response has left. A client that closes its sending side still receives the answers to what it already sent.

Each worker checks its connections every HTTP_SWEEP_MS and closes:

setIdleTimeout(0), setRequestTimeout(0) and setFirstByteTimeout(0) remove the limits. On Windows only the idle limit applies, as the socket's receive timeout.

Limits and errors

A request the server cannot serve gets an error response and its connection is closed:

StatusWhen
400Malformed request line or header (a line without :, a space or a control character in a header name, a folded header line, a 0 byte in the headers), a Content-Length that is not a number, or two Content-Length headers.
408The request did not arrive in full within the request timeout.
413The request (headers and body together) is larger than HTTP_MAX_REQUEST bytes (64 KiB).
431More than HTTP_MAX_HEADERS headers (100).
501A Transfer-Encoding header: request bodies sent in chunks are not supported.

The strict rules on Content-Length, Transfer-Encoding and header names are not pedantry: behind a proxy, a header that the proxy and the server read differently lets a client hide a second request inside the first (request smuggling). Refusing them closes that door.

Constants

NameValueMeaning
HTTP_MAX_REQUEST65536Largest request in bytes, headers and body together; larger ones get 413.
HTTP_MAX_FDS4096Connections per worker: a worker closes at once a client whose descriptor is not below this.
HTTP_MAX_EVENTS64Events read by one epoll_pwait.
HTTP_MAX_HEADERS100Most headers in a request; more get 431.
HTTP_DEFAULT_SESSION_IDLE_MS1800000Default idle limit of a session (30 minutes).
HTTP_DEFAULT_SESSION_MAX_MS86400000Default maximum lifetime of a session (24 hours).
HTTP_DEFAULT_BACKLOG511listen queue when setListen is not called.
HTTP_DEFAULT_IDLE_TIMEOUT_MS15000Default of setIdleTimeout, in milliseconds.
HTTP_DEFAULT_REQUEST_TIMEOUT_MS10000Default of setRequestTimeout, in milliseconds.
HTTP_DEFAULT_FIRST_BYTE_TIMEOUT_MS5000Default of setFirstByteTimeout, in milliseconds.
HTTP_SWEEP_MS1000How often a worker looks for expired connections.
HTTP_RBUF_KEEP_MS5000How long a closed descriptor keeps its own receive buffer, in milliseconds.
HTTP_KILL_SETTLE_MS100After a worker killed by SIGKILL, how long each round waits for the others that die with it.
HTTP_KILL_SETTLE_MAX_MS2000The longest the supervisor waits before deciding.
HTTP_RESPAWN_WINDOW_MS1000Restarts of crashed workers beyond ncoworker within this window wait for the window to end.
HTTP_PHASE_BEFORE0req.phase while a middleware runs before the route.
HTTP_PHASE_AFTER1req.phase while a middleware runs after the route.
HTTP_EINTR-4
HTTP_EAGAIN-11
HTTP_EPOLLIN1
HTTP_EPOLLOUT4
HTTP_EPOLLERR8
HTTP_EPOLLHUP16
HTTP_EPOLLRDHUP8192
HTTP_EPOLLEXCLUSIVE268435456
HTTP_EPOLL_CTL_ADD1
HTTP_EPOLL_CTL_DEL2
HTTP_EPOLL_CTL_MOD3
HTTP_O_NONBLOCK2048
HTTP_CLOEXEC524288
HTTP_EPOLL_EVENT_SIZEaarch64 16, 12
HTTP_EPOLL_DATA_OFFaarch64 8, 4

The constants of cookies and sessions are on the pages of libstd/http/cookies and libstd/http/session.

Classes

class
HttpRequest

One request, passed to routes and middleware. The request: action (the method), path, query, version, headers (an sdict with lower-case names; read it with getHeader), cookies (the request's Cookies, which also collects the cookies to send back), body, keep_alive. The session: session_id, session_data, session_size, session_flags; use the session* methods instead of the fields. The response, which routes and middleware may change: status, content_type, response_body, and response_headers (fill it with setResponseHeader; its table stays 0 until the first header). phase is the middleware phase. req_http holds the raw headers.

    req_http str
    size_pack int
    fd_sock SOCKET
    action str
    version str
    path str
    query str
    body str
    headers str
    cookies Cookies
    keep_alive int
    bad int
    session_on int
    session_id str
    session_data Sdict
    session_size long
    session_flags int
    status int
    content_type str
    response_body str
    response_headers Sdict
    phase int
    getSock &HttpRequestGetSock
    getVersion &HttpRequestGetVersion
    getAction &HttpRequestGetAction
    getPath &HttpRequestGetPath
    getQuery &HttpRequestGetQuery
    getHeader &HttpRequestGetHeader
    close &HttpRequestCloseSock
    setResponseHeader &HttpRequestSetResponseHeader
    hasResponseHeader &HttpRequestHasResponseHeader
    sessionId &HttpRequestSessionId
    sessionGet &HttpRequestSessionGet
    sessionHas &HttpRequestSessionHas
    sessionSet &HttpRequestSessionSet
    sessionDel &HttpRequestSessionDel
    sessionRegenerate &HttpRequestSessionRegenerate
    sessionDestroy &HttpRequestSessionDestroy
class
HttpServer

The server: create it with HttpServer(a, b, c, d, port), configure it with its methods, then call run().

    fd_sock SOCKET
    saddr_in Sockaddr_in
    len_queue int
    door int
    ip int[4]
    map_middleware str
    order_middleware List
    map_path_function str
    map_css_files str
    map_js_files str
    map_files str
    error_pages str
    default_headers str
    default_header_lines str
    base_dir str
    template_dir str
    static_dir str
    ncoworker long
    supervisor_pid int
    worker_pid int
    idle_timeout_ms long
    request_timeout_ms long
    first_byte_timeout_ms long
    now_ms long
    sessions str
    session_capacity long
    session_slots long
    session_idle_ms long
    session_max_ms long
    setNumCoworker &HttpServerSetNumCoworker
    getNumCoworker &HttpServerGetNumCoworker
    addMiddleWare &HttpServerAddMiddleWare
    delMiddleWare &HttpServerDelMiddleWare
    addMapsFunction &HttpServerMapsFunctionAdd
    delMapsFunction &HttpServerMapsFunctionDel
    addMapJs &HttpServerMapsStaticJsAdd
    delMapJs &HttpServerMapsStaticJsDel
    addMapCss &HttpServerMapsStaticCssAdd
    delMapCss &HttpServerMapsStaticCssDel
    addMapFile &HttpServerMapsStaticFileAdd
    delMapFile &HttpServerMapsStaticFileDel
    getBaseDirTemplate &HttpServerGetTemplates
    setBaseDirTemplate &HttpServerSetTemplates
    getBaseDirStatic &HttpServerGetStatics
    setBaseDirStatic &HttpServerSetStatics
    setBaseDir &HttpServerSetBaseDir
    getBaseDir &HttpServerGetBaseDir
    setErrorPage &HttpServerSetErrorPage
    setDefaultHeader &HttpServerSetDefaultHeader
    page &HttpServerPage
    setDoor &HttpServerSetDoor
    getDoor &HttpServerGetDoor
    getIp &HttpServerGetIp
    setIp &HttpServerSetIp
    setListen &HttpServerSetListen
    getListen &HttpServerGetListen
    setIdleTimeout &HttpServerSetIdleTimeout
    getIdleTimeout &HttpServerGetIdleTimeout
    setRequestTimeout &HttpServerSetRequestTimeout
    getRequestTimeout &HttpServerGetRequestTimeout
    setFirstByteTimeout &HttpServerSetFirstByteTimeout
    getFirstByteTimeout &HttpServerGetFirstByteTimeout
    setBind &HttpServerSetBind
    enableSessions &HttpServerEnableSessions
    setSessionTimeouts &HttpServerSetSessionTimeouts
    getSessionCount &HttpServerGetSessionCount
    dumpSessions &HttpServerDumpSessions
    elaborateReq &HttpRequestElaborateReq
    init_workers &HttpServerInitWorkers
    own_listener &HttpServerOwnListener
    run &HttpServerRun
    close &HttpServerCloseSock
class
HttpConn

Internal: the state of one open connection in a worker (receive buffer, response being sent, timestamps for the timeouts).

    fd SOCKET
    rbuf str
    rlen long
    wbuf str
    wlen long
    woff long
    close_after int
    want_out int
    active int
    last_ms long
    req_start_ms long
    eof int
    scratch int
    fresh int

Functions

def http_status_text(status: int) -> str

The reason phrase of a status code (404 -> "Not Found"), "Unknown" for a code it does not know.

def http_guess_content_type(path: str) -> str

The Content-Type for a file name from its extension (.html, .css, .js, .json, .png, .jpg, .svg, .ico, .pdf, .txt), application/octet-stream otherwise. For routes that serve files: req.content_type = http_guess_content_type(file).

def HttpServerSetNumCoworker(self: HttpServer, num_coworker: long) -> None
server.setNumCoworker(n): number of worker processes started by run() (at least 1). One per CPU is usually right.
def HttpServerGetNumCoworker(self: HttpServer) -> long
server.getNumCoworker(): the number of workers set.
def HttpServerMapsStaticJsAdd(self: HttpServer, logical_js: str, fs_file: str) -> None
server.addMapJs(path, file): serves file as application/javascript at path. A path already mapped is an error: it prints a message and exits.
def HttpServerMapsStaticJsDel(self: HttpServer, logical_js: str) -> None
server.delMapJs(path): removes a JavaScript mapping; an unknown path prints a message and exits.
def HttpServerMapsStaticCssAdd(self: HttpServer, logical_css: str, fs_file: str) -> None
server.addMapCss(path, file): serves file as text/css at path. A path already mapped is an error: it prints a message and exits.
def HttpServerMapsStaticCssDel(self: HttpServer, logical_css: str) -> None
server.delMapCss(path): removes a CSS mapping; an unknown path prints a message and exits.
def HttpServerMapsStaticFileAdd(self: HttpServer, logical_path: str, fs_file: str) -> None
server.addMapFile(path, file): serves file at path, with the Content-Type of its extension. A relative file is looked up in the base directory. A path already mapped is an error: it prints a message and exits.
def HttpServerMapsStaticFileDel(self: HttpServer, logical_path: str) -> None
server.delMapFile(path): removes a file mapping; an unknown path prints a message and exits.
def HttpServerSetBaseDir(self: HttpServer, directory: str) -> None
server.setBaseDir(dir): the directory where relative file names are looked up; "" (the default) for the working directory.
def HttpServerGetBaseDir(self: HttpServer) -> str
server.getBaseDir(): the base directory, "" if none was set.
def HttpServerSetTemplates(self: HttpServer, directory: str) -> None
server.setBaseDirTemplate(dir): the directory of the pages read by page and setErrorPage, relative to the base directory or absolute; "" (the default) for the base directory itself.
def HttpServerGetTemplates(self: HttpServer) -> str
server.getBaseDirTemplate(): the template directory joined to the base directory.
def HttpServerSetStatics(self: HttpServer, directory: str) -> None
server.setBaseDirStatic(dir): the directory of the files of addMapCss, addMapJs and addMapFile, relative to the base directory or absolute; "" (the default) for the base directory itself.
def HttpServerGetStatics(self: HttpServer) -> str
server.getBaseDirStatic(): the static directory joined to the base directory.
def HttpServerSetErrorPage(self: HttpServer, status: int, fs_file: str) -> None
server.setErrorPage(status, file): the page used as the body of responses with status and an empty body. A status outside 400-599 prints a message and exits.
def HttpServerSetDefaultHeader(self: HttpServer, name: str, value: str) -> int
server.setDefaultHeader(name, value): adds a header to every response, or replaces the one with the same name (any case). Call it before run(). Returns 0 and adds nothing for an invalid name, a header the library writes itself or a value with control characters (see Response headers above).
def HttpServerPage(self: HttpServer, req: HttpRequest, name: str) -> str
self.page(req, name): the content of name in the base directory, to return from a route. A missing file, or a name that would leave the base directory, sets req.status to 404 and returns "".
def HttpServerAddMiddleWare(self: HttpServer, identifier: str, function: str) -> None
server.addMiddleWare(name, function): adds a middleware &(HttpServer, HttpRequest) -> HttpRequest after the existing ones (see Middleware above). A name already in use prints a message and exits.
def HttpServerDelMiddleWare(self: HttpServer, identifier: str) -> None
server.delMiddleWare(name): removes a middleware, keeping the order of the others. An unknown name prints a message and exits.
def HttpRequestElaborateReq(self: HttpServer, req: HttpRequest) -> str
server.elaborateReq(req): runs middleware and route for a parsed request and returns the whole response, headers and body. Called by the workers; useful to test routes without a socket.
def HttpServerInitWorkers(self: HttpServer) -> long
server.init_workers(): called by run(). Starts the workers and returns their number (1, 2, ...) in each of them; in the supervisor it never returns.
def HttpServerOwnListener(self: HttpServer) -> None
server.own_listener(): called by run() in each Linux worker: replaces the inherited listening socket with the worker's own (SO_REUSEPORT).
def HttpServerRun(self: HttpServer) -> None
server.run(): checks that the base, template and static directories exist, then binds and listens (on error it prints a message and exits), starts the workers and serves forever. Never returns: in the calling process it runs the supervisor.
def HttpServerMapsFunctionAdd(self: HttpServer, virtual_path: str, name_function: str) -> None
server.addMapsFunction(path, function): function answers requests for exactly path. Adding the same path again replaces the function.
def HttpServerMapsFunctionDel(self: HttpServer, virtual_path: str) -> None
server.delMapsFunction(path): removes a route; nothing happens if there is none.
def HttpServerGetIp(self: HttpServer) -> str
server.getIp(): the address as text, "127.0.0.1".
def HttpServerSetIp(self: HttpServer, first: int, second: int, third: int, fourth: int) -> None
server.setIp(a, b, c, d): the address to listen on; each octet must be 0-255, otherwise it prints a message and exits.
def HttpServerSetDoor(self: HttpServer, door: int) -> None
server.setDoor(port): the port to listen on (0-65535).
def HttpServerGetDoor(self: HttpServer) -> int
server.getDoor(): the port.
def HttpServerSetListen(self: HttpServer, new_len_queue: int) -> None
server.setListen(n): the listen queue of each listening socket (default HTTP_DEFAULT_BACKLOG).
def HttpServerGetListen(self: HttpServer) -> int
server.getListen(): the listen queue.
def HttpServerSetIdleTimeout(self: HttpServer, ms: long) -> None
server.setIdleTimeout(ms): closes connections with no activity for ms milliseconds, keep-alive ones included. 0 removes the limit.
def HttpServerGetIdleTimeout(self: HttpServer) -> long
server.getIdleTimeout(): the idle limit in milliseconds.
def HttpServerSetRequestTimeout(self: HttpServer, ms: long) -> None
server.setRequestTimeout(ms): a request must arrive in full within ms milliseconds of its first byte, otherwise the client gets 408 and the connection is closed. 0 removes the limit.
def HttpServerGetRequestTimeout(self: HttpServer) -> long
server.getRequestTimeout(): the request limit in milliseconds.
def HttpServerSetFirstByteTimeout(self: HttpServer, ms: long) -> None
server.setFirstByteTimeout(ms): closes a new connection that has sent nothing for ms milliseconds. After the first byte the request and idle limits apply. 0 removes the limit. Linux only.
def HttpServerGetFirstByteTimeout(self: HttpServer) -> long
server.getFirstByteTimeout(): the first-byte limit in milliseconds.
def HttpServerSetBind(self: HttpServer, saddr_in: Sockaddr_in) -> None
server.setBind(addr): copies family, port and address from a Sockaddr_in prepared by hand.
def HttpServerCloseSock(self: HttpServer) -> None
server.close(): closes the server's listening socket.
def HttpServer(first: int, second: int, third: int, fourth: int, door: int) -> HttpServer

Creates the server on the IPv4 address first.second.third.fourth and door (the port), with the default backlog and timeouts. The socket is created here and bound by run().

def HttpRequestCloseSock(self: HttpRequest) -> None
req.close(): closes the client's socket. Routes do not need it: the server closes connections itself.
def HttpRequestGetVersion(self: HttpRequest) -> str
req.getVersion(): "HTTP/1.1" or "HTTP/1.0".
def HttpRequestGetSock(self: HttpRequest) -> SOCKET
req.getSock(): the client's socket.
def HttpRequestGetAction(self: HttpRequest) -> str
req.getAction(): the method, "GET", "POST", ...
def HttpRequestGetPath(self: HttpRequest) -> str
req.getPath(): the path, without the query string and not percent-decoded.
def HttpRequestGetQuery(self: HttpRequest) -> str
req.getQuery(): what follows ? in the target, "" if nothing; not decoded.
def HttpRequestGetHeader(self: HttpRequest, name: str) -> str
req.getHeader(name): the value of a request header, whatever the case of name; "" if absent. With a header repeated, the last one, except Cookie: repeated Cookie headers are joined with "; ".
def HttpRequestSetResponseHeader(self: HttpRequest, name: str, value: str) -> int
req.setResponseHeader(name, value): adds a header to this response, or replaces the one with the same name (any case), including a server default. Returns 0 and adds nothing for an invalid name, a header the library writes itself or a value with control characters (see Response headers above).
def HttpRequestHasResponseHeader(self: HttpRequest, name: str) -> int
req.hasResponseHeader(name): 1 if setResponseHeader already added a header with this name (any case) to the response. It does not see the server defaults.
def HttpRequest(fd_sock: SOCKET, head: str) -> HttpRequest

Builds a request from its headers, everything before \r\n\r\n. When the request cannot be served, req.bad holds the status to answer (400, 431 or 501), otherwise 0. The workers call it for every request.

Internal helpers

Used by the functions above; not meant to be called directly.