http.server.new

http.server

new(config, handle, app) -> server, err

Create a new HTTP server instance

Creates and configures an HTTP server. The handle function is called for each request with (method, query, args, headers, body, context) and must return content, status, response_headers. The args string is the request's query string without the leading ?. The optional app table is an opaque application context passed to the handler as context.app — the place for process-lifetime state such as stores and caches.

Several server instances (each with its own handler, TLS identities and connection budget) can share one event loop via serve_all; a single instance may also bind several addresses via listen.

The config table may override these defaults:

TLS configuration (ssl field):

{
  default = { cert = "path/to/cert", key = "path/to/key" },
  hosts = {
    ["domain.com"] = { cert = "...", key = "..." },
  },
}

The server uses a coroutine-per-connection model: each accepted connection is handled in a spawned coroutine within lev.run().

local server = require("http.server")

local srv, err = server.new(
    {
        ip   = "0.0.0.0",
        port = 8443,
        ssl  = {
            default = {
                cert = "/etc/tls/cert.pem",
                key  = "/etc/tls/key.pem",
            },
        },
    },
    function(method, query, args, headers, body, ctx)
        return "Hello!", 200, { ["content-type"] = "text/plain" }
    end
)
if not srv then error(err) end
srv:serve()  -- blocks forever