### Basic HTTP Request with http.compat.socket Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.compat.socket.md Demonstrates a simple HTTP GET request using the 'simple' interface of the http.compat.socket module. This example shows how to fetch content from a URL and print the HTTP status code and the body length. It assumes a standard Lua environment. ```lua local socket_http = require "http.compat.socket" local body, code = assert(socket_http.request("http://lua.org")) print(code, #body) --> 200, 2514 ``` -------------------------------- ### Install local copy of lua-http Source: https://github.com/daurnimator/lua-http/blob/master/README.md Install the locally developed version of lua-http using the rockspec file. ```bash $ luarocks make http-scm.rockspec ``` -------------------------------- ### Install development dependencies Source: https://github.com/daurnimator/lua-http/blob/master/README.md Install the necessary development dependencies for lua-http using the provided rockspec file. ```bash $ luarocks install --only-deps http-scm-0.rockspec ``` -------------------------------- ### Bitwise AND Operation Example Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.bit.md Demonstrates how to use the `band` function from the `http.bit` module to perform a bitwise AND operation. Ensure the `http.bit` module is required before use. ```lua local bit = require "http.bit" print(bit.band(1, 3)) --> 1 ``` -------------------------------- ### Install lua-http using luarocks Source: https://github.com/daurnimator/lua-http/blob/master/README.md Install the lua-http library and its runtime dependencies using the luarocks package manager. ```bash $ luarocks install http ``` -------------------------------- ### Install LuaRocks and HTTP Library on Amazon Linux Source: https://github.com/daurnimator/lua-http/wiki/Installing-on-Amazon-Linux Installs development tools, LuaRocks, and the http library on Amazon Linux. Ensure you have a compatible Amazon Linux environment. ```bash cd yum install lua-devel unzip gcc openssl-devel m4 ca-certificates curl -L -O https://github.com/luarocks/luarocks/archive/v2.4.2.tar.gz tar -xzvf v2.4.2.tar.gz cd luarocks-2.4.2/ ./configure make bootstrap luarocks install http ``` -------------------------------- ### Making an HTTP Request with http.compat.prosody Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.compat.prosody.md Demonstrates how to use the `http.compat.prosody.request` function to make a GET request and process the response within a cqueue. Ensure a cqueue is running before calling this function. ```lua local prosody_http = require "http.compat.prosody" local cqueues = require "cqueues" local cq = cqueues.new() cq:wrap(function() prosody_http.request("http://httpbin.org/ip", {}, function(b, c, r) print(c) --> 200 print(b) --> {"origin": "123.123.123.123"} end) end) assert(cq:loop()) ``` -------------------------------- ### Run tests and view coverage Source: https://github.com/daurnimator/lua-http/blob/master/README.md Execute the test suite and generate a coverage report for the lua-http project. Ensure testing tools are installed first. ```bash $ busted -c $ luacov && less luacov.report.out ``` -------------------------------- ### Accessing HTTP Reason Phrases Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h1_reason_phrases.md Demonstrates how to require and use the http.h1_reason_phrases module to get the reason phrase for a given HTTP status code. Handles both known and unknown codes. ```lua local reason_phrases = require "http.h1_reason_phrases" print(reason_phrases["200"]) --> "OK" print(reason_phrases["342"]) --> "Unassigned" ``` -------------------------------- ### headers:get(name) Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.headers.md Retrieves all values for a given header name, returning them as multiple return values. ```APIDOC ## headers:get(name) ### Description Returns all headers with the given name as multiple return values. ### Method `headers:get(name)` ``` -------------------------------- ### http.cookie.store:get Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.cookie.md Retrieves a specific cookie's value from the store. ```APIDOC ## http.cookie.store:get ### Description Returns the cookie value for the cookie stored for the passed `domain`, `path` and `name`. ### Parameters - **domain** (string) - Required - The domain of the cookie to retrieve. - **path** (string) - Required - The path of the cookie to retrieve. - **name** (string) - Required - The name of the cookie to retrieve. ### Response - **value** (string | nil) - The value of the cookie, or `nil` if not found. ``` -------------------------------- ### Get All Headers with Same Name as Sequence Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.headers.md Retrieve all header values for a given name as a sequence table. This is useful when a header can appear multiple times, like 'Set-Cookie'. The table includes a '.n' field for the count. ```lua local http_headers = require "http.headers" local myheaders = http_headers.new() myheaders:append(":status", "200") myheaders:append("set-cookie", "foo=bar") myheaders:append("connection", "close") myheaders:append("set-cookie", "baz=qux") local mysequence = myheaders:get_as_sequence("set-cookie") --[[ mysequence will be: {n = 2; "foo=bar"; "baz=qux"} ]] ``` -------------------------------- ### Connect to Local HTTP Server Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.client.md Establishes a connection to a local HTTP server on a specified port. Ensure the server is running before executing. ```lua local http_client = require "http.client" local myconnection = http_client.connect { host = "localhost"; port = 8000; ls = false; } ``` -------------------------------- ### server:listen Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.server.md Initializes the server socket and performs any necessary DNS resolution. This method must be called before `step()` or `loop()` if `localname()` is called prior. ```APIDOC ## server:listen(timeout) Initializes the server socket and if required, resolves DNS. `server:listen()` is required if [*localname*](#http.server:localname) is called before [*step*](#http.server:step) or [*loop*](#http.server:loop). On error, returns `nil`, an error message and an error number. ``` -------------------------------- ### http.hpack.new Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.hpack.md Creates a new HPACK context. Optionally initializes with a given header table size. ```APIDOC ## http.hpack.new ### Description Creates a new HPACK context. Optionally initializes with a given header table size. ### Parameters #### Path Parameters - **SETTINGS_HEADER_TABLE_SIZE** (number) - Optional - The initial size of the dynamic table. ``` -------------------------------- ### connection:timeout() Source: https://github.com/daurnimator/lua-http/blob/master/doc/interfaces/connection.md Gets the current timeout value for the connection. ```APIDOC ## connection:timeout() ### Description Gets the current timeout value for the connection. ``` -------------------------------- ### Compress and Decompress String with http.zlib Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.zlib.md Demonstrates how to use http.zlib to compress a string using deflate and then decompress it back to the original using inflate. Asserts that the original and uncompressed strings are identical. ```lua local zlib = require "http.zlib" local original = "the racecar raced around the racecar track" local deflater = zlib.deflate() local compressed = deflater(original, true) print(#original, #compressed) -- compressed should be smaller local inflater = zlib.inflate() local uncompressed = inflater(compressed, true) assert(original == uncompressed) ``` -------------------------------- ### h2_stream:peername() Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h2_stream.md Gets the peer address of the stream. See stream:peername(). ```APIDOC ## h2_stream:peername() See [`stream:peername()`](#stream:peername) ``` -------------------------------- ### h2_stream:localname() Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h2_stream.md Gets the local address of the stream. See stream:localname(). ```APIDOC ## h2_stream:localname() See [`stream:localname()`](#stream:localname) ``` -------------------------------- ### http.h1_stream.max_header_lines Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h1_stream.md Sets or gets the maximum number of header lines to read. The default value is 100. ```APIDOC ## http.h1_stream.max_header_lines The maximum number of header lines to read. Default is `100`. ``` -------------------------------- ### Set up Lua Paths Source: https://github.com/daurnimator/lua-http/wiki/Installing-on-Amazon-Linux Configures the environment variables for LuaRocks. Run this command in your shell to make Lua modules accessible. ```bash eval $(luarocks path) ``` -------------------------------- ### http.server.listen Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.server.md Creates a new socket and returns an HTTP server that will accept() from it. This function is an alternative to `new()` when you need the server to manage socket creation. ```APIDOC ## http.server.listen(options) Creates a new socket and returns an HTTP server that will accept() from it. Parameters are the same as [`new(options)`](#http.server.new) except instead of `.socket` you provide the following: ### Parameters - `.host` (*string*): Local IP address in dotted decimal or IPV6 notation. This value is required if `.path` is not specified. - `.port` (*number*): IP port for the local socket. Specify 0 for automatic port selection. Ports 1-1024 require the application has root privilege to run. Maximum value is 65535. If `.tls == nil` then this value is required. Otherwise, the defaults are: - `80` if `.tls == false` - `443` if `.tls == true` - `.path` (*string*): Path to UNIX a socket. This value is required if `.host` is not specified. - `.family` (*string*): Protocol family. Default is `"AF_INET"` - `.v6only` (*boolean*): Specify `true` to limit all connections to ipv6 only (no ipv4-mapped-ipv6). Default is `false`. - `.mode` (*string*): `fchmod` or `chmod` socket after creating UNIX domain socket. - `.mask` (*boolean*): Set and restore umask when binding UNIX domain socket. - `.unlink` (*boolean*): `true` means unlink socket path before binding. - `.reuseaddr` (*boolean*): Turn on `SO_REUSEADDR` flag. - `.reuseport` (*boolean*): Turn on `SO_REUSEPORT` flag. ``` -------------------------------- ### http.server.new Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.server.md Creates a new instance of an HTTP server listening on a given socket. It configures various callbacks and options for handling client connections and requests. ```APIDOC ## http.server.new(options) Creates a new instance of an HTTP server listening on the given socket. ### Parameters - `.socket` (*cqueues.socket*): the socket that `accept()` will be called on - `.onerror` (*function*): Function that will be called when an error occurs (default handler throws an error). - `.onstream` (*function*): Callback function for handling a new client request. The function receives the [*server*](#http.server) and the new [*stream*](#stream) as parameters. If the callback throws an error it will be reported from [`:step()`](#http.server:step) or [`:loop()`](#http.server:loop) - `.tls` (*boolean*): Specifies if the system should use Transport Layer Security. Values are: - `nil`: Allow both tls and non-tls connections - `true`: Allows tls connections only - `false`: Allows non-tls connections only - `.ctx` (*context object*): An `openssl.ssl.context` object to use for tls connections. If `nil` is passed, a self-signed context will be generated. - `.connection_setup_timeout` (*number*): Timeout (in seconds) to wait for client to send first bytes and/or complete TLS handshake. Default is 10 seconds. - `.intra_stream_timeout` (*number*): Timeout (in seconds) to wait for a new [*stream*](#stream) on an idle connection before giving up and closing the connection - `.version` (*number*): The http version to allow to connect (default: any) - `.cq` (*cqueue*): A cqueues controller to use as a main loop. The default is a new controller for the server. - `.max_concurrent` (*number*): Maximum number of connections to allow live at a time. Default is infinity. ``` -------------------------------- ### headers:sort() Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.headers.md Sorts the header fields within the headers object. Headers starting with ':' are placed first, followed by alphabetical sorting of names, then values, and finally the `never_index` flag. ```APIDOC ## headers:sort() ### Description Sort the list of headers by their field name, ordering those starting with `:` first. If `name`s are equal then sort by `value`, then by `never_index`. ### Method `headers:sort()` ``` -------------------------------- ### Establish WebSocket Communication Source: https://github.com/daurnimator/lua-http/blob/master/doc/introduction.md Creates a new WebSocket client to communicate with a server. Connect, send data, receive data, and close the connection in sequence. ```lua local websocket = require "http.websocket" local ws = websocket.new_from_uri("wss://echo.websocket.org") assert(ws:connect()) assert(ws:send("koo-eee!")) local data = assert(ws:receive()) assert(data == "koo-eee!") assert(ws:close()) ``` -------------------------------- ### http.client.connect Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.client.md Establishes a new connection to an HTTP server, returning a connection object that can be used to create streams for request/response exchanges. ```APIDOC ## http.client.connect(options, timeout) ### Description This function returns a new connection to an HTTP server. Once a connection has been opened, a stream can be created to start a request/response exchange. Please see [`h1_stream.new_stream`](#h1_stream.new_stream) and [`h2_stream.new_stream`](#h2_stream.new_stream) for more information about creating streams. ### Parameters #### Parameters - **options** (table) - Description: a table containing the options to [`http.client.negotiate`](#http.client.negotiate), plus the following: - **family** (integer, optional): socket family to use. defaults to `AF_INET` - **host** (string) - Description: host to connect to. may be either a hostname or an IP address - **port** (string|integer) - Description: port to connect to in numeric form e.g. `"80"` or `80` - **path** (string) - Description: path to connect to (UNIX sockets) - **v6only** (boolean, optional): if the `IPV6_V6ONLY` flag should be set on the underlying socket. - **bind** (string, optional): the local outgoing address and optionally port to bind in the form of `"address[:port]"`, IPv6 addresses may be specified via square bracket notation. e.g. `"127.0.0.1"`, `"127.0.0.1:50000"`, `"[::1]:30000"`. - **timeout** (number, optional) - Description: is the maximum amount of time (in seconds) to allow for connection to be established. This includes time for DNS lookup, connection, TLS negotiation (if TLS enabled) and in the case of HTTP 2: settings exchange. ### Request Example Connect to a local HTTP server running on port 8000 ```lua local http_client = require "http.client" local myconnection = http_client.connect { host = "localhost"; port = 8000; ls = false; } ``` ``` -------------------------------- ### is_safe_method Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.util.md Returns a boolean indicating if the passed string method is a "safe" HTTP method. Safe methods are typically GET, HEAD, and OPTIONS, which do not alter server state. ```APIDOC ## is_safe_method(method) ### Description Returns a boolean indicating if the passed string `method` is a "safe" method. See [RFC 7231 section 4.2.1](https://tools.ietf.org/html/rfc7231#section-4.2.1) for more information. ### Method N/A (Function Call) ### Parameters #### Path Parameters - **method** (string) - Required - The HTTP method to check. ``` -------------------------------- ### http.proxies.new Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.proxies.md Creates and returns a new, empty proxies object. This object can then be used to manage proxy configurations. ```APIDOC ## http.proxies.new ### Description Returns an empty 'proxies' object. ### Method `new()` ### Returns - `proxies` (object) - An empty proxies object. ``` -------------------------------- ### http.cookie.new_store Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.cookie.md Creates a new, empty cookie store. ```APIDOC ## http.cookie.new_store ### Description Creates a new cookie store. Cookies are unique for a tuple of domain, path and name; although multiple cookies with the same name may exist in a request due to overlapping paths or domains. ### Response - **store** (object) - A new cookie store object. ``` -------------------------------- ### http.socks.fdopen Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.socks.md Creates a http.socks object from an existing cqueues.socket. ```APIDOC ## http.socks.fdopen(socket) ### Description Initializes a http.socks object using an already established socket. ### Parameters #### Path Parameters - **socket** (cqueues.socket) - Required - An existing cqueues socket object. ### Returns - *http.socks* object wrapping the provided socket. ``` -------------------------------- ### server:step(timeout) Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.server.md Advances the server's main loop by one iteration, accepting new clients, processing streams, and running onstream handlers. It blocks for up to the specified timeout. Returns nil, an error message, and an error number on failure. ```APIDOC ## `server:step(timeout)` ### Description Step once through server's main loop: any waiting clients will be `accept()`-ed, any pending streams will start getting processed, and each `onstream` handler will get be run at most once. This method will block for *up to* `timeout` seconds. On error, returns `nil`, an error message and an error number. ### Parameters #### Path Parameters - **timeout** (number) - Required - The maximum time in seconds to block. ### Method `server:step(timeout)` ``` -------------------------------- ### server:resume() Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.server.md Resumes a paused server, allowing it to process new client requests. This is the counterpart to the pause() method. ```APIDOC ## `server:resume()` ### Description Resumes a [*paused*](#http.server:pause) `server` and processes new client requests. ### Method `server:resume()` ``` -------------------------------- ### proxies:choose Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.proxies.md Determines the appropriate proxy URI for a given network scheme and host based on the current proxy configuration. ```APIDOC ## proxies:choose ### Description Returns the proxy to use for the given `scheme` and `host` as a URI. ### Method `choose(scheme, host)` ### Parameters #### Query Parameters - `scheme` (string) - Required - The network scheme (e.g., 'http', 'https'). - `host` (string) - Required - The host to connect to. ### Returns - `proxy_uri` (string or nil) - The URI of the proxy to use, or nil if no proxy is needed. ``` -------------------------------- ### Retrieve a Document with http.request Source: https://github.com/daurnimator/lua-http/blob/master/doc/introduction.md Fetches an HTTP resource by constructing a request object from a URI and evaluating it. Ensure the response status is checked before processing the body. ```lua local http_request = require "http.request" local headers, stream = assert(http_request.new_from_uri("http://example.com"):go()) local body = assert(stream:get_body_as_string()) if headers:get ":status" ~= "200" then error(body) end print(body) ``` -------------------------------- ### http.client.negotiate Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.client.md Negotiates HTTP settings with the remote server and instantiates the encryption tunnel if TLS is specified. ```APIDOC ## http.client.negotiate(socket, options, timeout) ### Description Negotiates the HTTP settings with the remote server. If TLS has been specified, this function instantiates the encryption tunnel. ### Parameters #### Parameters - **socket** (cqueues socket object) - Description: a cqueues socket object - **options** (table) - Description: a table containing: - **tls** (boolean, optional): Should TLS be used? defaults to `false` - **ctx** (userdata, optional): the `SSL_CTX*` to use if `.tls` is `true`. If `.ctx` is `nil` then a default context will be used. - **sendname** (string|boolean, optional): the [TLS SNI](https://en.wikipedia.org/wiki/Server_Name_Indication) host to send. defaults to `true` (`true` indicates to copy the `.host` field as long as it is **not** an IP, `false` disables SNI) - **version** (`nil`|1.0|1.1|2, optional): HTTP version to use. `nil`: attempts HTTP 2 and falls back to HTTP 1.1; `1.0`; `1.1`; `2` - **h2_settings** (table, optional): HTTP 2 settings to use. See [*http.h2_connection*](#http.h2_connection) for details - **timeout** (number, optional): Description: maximum amount of time (in seconds) to allow for negotiation. ``` -------------------------------- ### store:load_from_file Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.cookie.md Loads cookie data from a file object into the store. The file should be in Netscape Cookiejar format. ```APIDOC ## store:load_from_file(file) ### Description Loads cookie data from the file object `file` into `store`. The file should be in the Netscape Cookiejar format. Invalid lines in the file are ignored. Returns `true` on success or passes along `nil, err, errno` if a `:read` call fails. ### Method (Not specified, likely a method call on a store object) ### Parameters - **file** (file object) - The file object to load cookie data from. ``` -------------------------------- ### websocket:connect Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.websocket.md Connects to a websocket server. This is typically called after a successful `new_from_uri`. ```APIDOC ## websocket:connect(timeout) ### Description Connect to a websocket server. ### Parameters #### Path Parameters - **timeout** (number, optional) - The timeout in seconds for the connection attempt. ### Returns - `boolean` - True on success, false on failure. ``` -------------------------------- ### http.tls.new_server_context() Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.tls.md Creates and returns a new luaossl SSL context specifically configured for use in HTTP server connections. ```APIDOC ## http.tls.new_server_context() ### Description Create and return a new luaossl SSL context useful for HTTP server connections. ### Method N/A (Function Call) ### Endpoint N/A ``` -------------------------------- ### http.h1_connection.new Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h1_connection.md Constructor for a new h1_connection. It takes a cqueues socket, a connection type string ('client' or 'server'), and a numeric HTTP version (1 or 1.1). ```APIDOC ## http.h1_connection.new ### Description Constructor for a new connection. Takes a cqueues socket object, a [connection type string](#connection.type) and a numeric HTTP version number. Valid values for the connection type are "client" and "server". Valid values for the version number are `1` and `1.1`. Returns the newly initialized connection object. ### Method `new(socket, conn_type, version)` ### Parameters * **socket** (cqueues socket) - The socket object for the connection. * **conn_type** (string) - The type of connection, either "client" or "server". * **version** (number) - The HTTP version, either `1` or `1.1`. ``` -------------------------------- ### http.h2_connection.new Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h2_connection.md Constructor for a new HTTP/2 connection. Initializes the connection in a non-connected state. ```APIDOC ## http.h2_connection.new ### Description Constructor for a new connection. Takes a cqueues socket object, a [connection type string](#connection.type) and an optional table of HTTP 2 settings. Returns the newly initialized connection object in a non-connected state. ### Parameters - **socket** (cqueues socket) - The socket object for the connection. - **conn_type** (string) - The type of connection. - **settings** (table, optional) - An optional table of HTTP 2 settings. ``` -------------------------------- ### http.tls.new_client_context() Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.tls.md Creates and returns a new luaossl SSL context specifically configured for use in HTTP client connections. ```APIDOC ## http.tls.new_client_context() ### Description Create and return a new luaossl SSL context useful for HTTP client connections. ### Method N/A (Function Call) ### Endpoint N/A ``` -------------------------------- ### socks:negotiate Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.socks.md Completes the SOCKS connection negotiation process. ```APIDOC ## socks:negotiate(host, port, timeout) ### Description Performs the SOCKS protocol negotiation to establish a connection to the target host and port. ### Parameters #### Path Parameters - **host** (string) - Required - The target host address. Will be resolved locally if `http.socks.needs_resolve` is true. - **port** (number) - Required - The target port number. - **timeout** (number) - Optional - The timeout in seconds for the negotiation. ### Returns - `nil`, error message, error number on failure. ``` -------------------------------- ### Clone lua-http repository Source: https://github.com/daurnimator/lua-http/blob/master/README.md Clone the lua-http source code from GitHub to begin development. ```bash $ git clone https://github.com/daurnimator/lua-http.git $ cd lua-http ``` -------------------------------- ### headers:dump(file, prefix) Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.headers.md Prints the contents of the headers object to a specified file or to standard error if no file is provided. Each header is printed on a new line, with an optional prefix. ```APIDOC ## headers:dump(file, prefix) ### Description Print the headers list to the given file, one per line. If `file` is not given, then print to `stderr`. `prefix` is prefixed to each line. ### Method `headers:dump(file, prefix)` ``` -------------------------------- ### http.socks.connect Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.socks.md Establishes a connection to a SOCKS server. Supports both local and remote host resolution based on the URI scheme. ```APIDOC ## http.socks.connect(uri) ### Description Establishes a connection to a SOCKS server. ### Parameters #### Path Parameters - **uri** (string) - Required - The address of the SOCKS server. Schemes like `socks5` and `socks5h` are supported. Userinfo in the URI will be used for authentication. ### Returns - *http.socks* object representing the SOCKS connection. ``` -------------------------------- ### http.h1_connection:onidle Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h1_connection.md See connection:onidle(new_handler). ```APIDOC ## http.h1_connection:onidle ### Description See [`connection:onidle(new_handler)`](#connection:onidle). ### Method `onidle(new_handler)` ### Parameters * **new_handler** (function) - The new handler function to be called when the connection is idle. ``` -------------------------------- ### server:loop(timeout) Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.server.md Runs the server in a blocking loop for a specified duration. The server continues to operate until explicitly paused, closed, or an error occurs. ```APIDOC ## `server:loop(timeout)` ### Description Run the server as a blocking loop for up to `timeout` seconds. The server will continue to listen and accept client requests until either [`:pause()`](#http.server:pause) or [`:close()`](#http.server:close) is called, or an error is experienced. ### Parameters #### Path Parameters - **timeout** (number) - Required - The maximum time in seconds to run the loop. ### Method `server:loop(timeout)` ``` -------------------------------- ### http.hsts.new_store Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.hsts.md Creates and returns a new HSTS store. This store is used to manage HSTS directives for various hosts. ```APIDOC ## http.hsts.new_store ### Description Creates and returns a new HSTS store. ### Returns - `hsts_store` - A new, empty HSTS store object. ``` -------------------------------- ### http.compat.prosody.request Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.compat.prosody.md Initiates an HTTP request. This function must be called from within a running cqueue. The callback function receives the response body, status code, and a request object. ```APIDOC ## http.compat.prosody.request(url, ex, callback) ### Description Initiates an HTTP request to the specified URL. The callback function is invoked upon completion, receiving the response body, status code, and the request object itself. ### Parameters #### Path Parameters - **url** (string) - Required - The URL to send the HTTP request to. - **ex** (table) - Optional - Additional options for the request (details not specified in source). - **callback** (function) - Required - A function to be called upon completion of the request. It receives three arguments: `body` (string), `code` (number), and `request` (http.request object). ### Method [Implicitly POST or GET based on typical HTTP request libraries, but not explicitly defined in source] ### Endpoint [Not applicable for SDK-style function calls] ### Request Example ```lua local prosody_http = require "http.compat.prosody" local cqueues = require "cqueues" local cq = cqueues.new() cq:wrap(function() prosody_http.request("http://httpbin.org/ip", {}, function(b, c, r) print(c) --> 200 print(b) --> {"origin": "123.123.123.123"} end) end) assert(cq:loop()) ``` ### Response #### Success Response - **body** (string) - The response body from the server. - **code** (number) - The HTTP status code of the response. - **request** (http.request) - The http.request object, passed to the callback on success and errors. #### Response Example [Response body depends on the URL and server, see example for a typical success case.] ``` -------------------------------- ### http.h1_connection:localname Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h1_connection.md See connection:localname(). ```APIDOC ## http.h1_connection:localname ### Description See [`connection:localname()`](#connection:localname). ### Method `localname()` ``` -------------------------------- ### http.h1_connection:connect Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h1_connection.md See connection:connect(timeout). ```APIDOC ## http.h1_connection:connect ### Description See [`connection:connect(timeout)`](#connection:connect). ### Method `connect(timeout)` ### Parameters * **timeout** (number) - The timeout value in seconds. ``` -------------------------------- ### Lint the code Source: https://github.com/daurnimator/lua-http/blob/master/README.md Check the lua-http code for common programming errors using luacheck. ```bash $ luacheck . ``` -------------------------------- ### websocket:accept Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.websocket.md Completes negotiation with a websocket client. This is typically called after a successful `new_from_stream`. ```APIDOC ## websocket:accept(options, timeout) ### Description Completes negotiation with a websocket client. ### Parameters #### Path Parameters - **options** (table, optional) - A table containing: - `headers` (`http.headers`, optional) - A headers object to use as a prototype for the response headers. - `protocols` (table, optional) - A lua table containing a sequence of protocols to allow from the client. - **timeout** (number, optional) - The timeout in seconds for the operation. ### Returns - `boolean` - True on success, false on failure. ``` -------------------------------- ### http.h1_connection:checktls Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h1_connection.md See connection:checktls(). ```APIDOC ## http.h1_connection:checktls ### Description See [`connection:checktls()`](#connection:checktls). ### Method `checktls()` ``` -------------------------------- ### Request Configuration Properties Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.request.md Properties to configure an http.request object. ```APIDOC ## Request Properties ### `request.host` #### Description The host this request should be sent to. ### `request.port` #### Description The port this request should be sent to. ### `request.bind` #### Description The local outgoing address and optionally port to bind in the form of `"address[:port]"`. Default is to allow the kernel to choose an address+port. IPv6 addresses may be specified via square bracket notation. e.g. `"127.0.0.1"`, `"127.0.0.1:50000"`, `"[::1]:30000"`. This option is rarely needed. Supplying an address can be used to manually select the network interface to make the request from, while supplying a port is only really used to interoperate with firewalls or devices that demand use of a certain port. ### `request.tls` #### Description A boolean indicating if TLS should be used. ### `request.ctx` #### Description An alternative `SSL_CTX*` to use. If not specified, uses the default TLS settings. ### `request.sendname` #### Description The TLS SNI host name used. ### `request.version` #### Description The HTTP version to use; leave as `nil` to auto-select. ### `request.proxy` #### Description Specifies the a proxy that the request will be made through. The value should be a URI or `false` to turn off proxying for the request. ### `request.headers` #### Description A [*http.headers*](#http.headers) object of headers that will be sent in the request. ### `request.hsts` #### Description The [*http.hsts*](#http.hsts) store that will be used to enforce HTTP strict transport security. An attempt will be made to add strict transport headers from a response to the store. Defaults to a shared store. ### `request.proxies` #### Description The [*http.proxies*](#http.proxies) object used to select a proxy for the request. Only consulted if `request.proxy` is `nil`. ### `request.cookie_store` #### Description The [*http.cookie.store*](#http.cookie.store) that will be used to find cookies for the request. An attempt will be made to add cookies from a response to the store. Defaults to a shared store. ### `request.is_top_level` #### Description A boolean flag indicating if this request is a "top level" request (See [RFC 6265bis-02 Section 5.2](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-02#section-5.2)). Defaults to `true`. ### `request.site_for_cookies` #### Description A string containing the host that should be considered as the "site for cookies" (See [RFC 6265bis-02 Section 5.2](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-02#section-5.2)), can be `nil` if unknown. Defaults to `nil`. ### `request.follow_redirects` #### Description Boolean indicating if `:go()` should follow redirects. Defaults to `true`. ### `request.expect_100_timeout` #### Description Number of seconds to wait for a 100 Continue response before proceeding to send a request body. Defaults to `1`. ### `request.max_redirects` #### Description Maximum number of redirects to follow before giving up. Defaults to `5`. Set to `math.huge` to not give up. ### `request.post301` #### Description Respect RFC 2616 Section 10.3.2 and **don't** convert POST requests into body-less GET requests when following a 301 redirect. The non-RFC behaviour is ubiquitous in web browsers and assumed by servers. Modern HTTP endpoints send status code 308 to indicate that they don't want the method to be changed. Defaults to `false`. ### `request.post302` #### Description Respect RFC 2616 Section 10.3.3 and **don't** convert POST requests into body-less GET requests when following a 302 redirect. The non-RFC behaviour is ubiquitous in web browsers and assumed by servers. Modern HTTP endpoints send status code 307 to indicate that they don't want the method to be changed. Defaults to `false`. ``` -------------------------------- ### Iterate Through Headers Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.headers.md Use the `each` method to iterate over all header fields, accessing their name, value, and sensitivity flag. This is useful for logging or processing all headers. ```lua local http_headers = require "http.headers" local myheaders = http_headers.new() myheaders:append(":status", "200") myheaders:append("set-cookie", "foo=bar") myheaders:append("connection", "close") myheaders:append("set-cookie", "baz=qux") for name, value, never_index in myheaders:each() do print(name, value, never_index) end --[[ prints: ":status", "200", false "set-cookie", "foo=bar", true "connection", "close", false "set-cookie", "baz=qux", true ]] ``` -------------------------------- ### http.h2_connection:onidle Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h2_connection.md See connection:onidle(new_handler). ```APIDOC ## h2_connection:onidle(new_handler) ### Description See [`connection:onidle(new_handler)`](#connection:onidle) ``` -------------------------------- ### http.h1_connection:events Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h1_connection.md See connection:events(). ```APIDOC ## http.h1_connection:events ### Description See [`connection:events()`](#connection:events). ### Method `events()` ``` -------------------------------- ### http.request.new_connect Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.request.md Creates a new http.request object for a CONNECT request. ```APIDOC ## http.request.new_connect(uri, connect_authority) ### Description Creates a new `http.request` object from the given URI that will perform a *CONNECT* request. ### Parameters #### Path Parameters - **uri** (string) - Required - The URI for the CONNECT request. - **connect_authority** (string) - Required - The authority to connect to. ``` -------------------------------- ### connection:connect(timeout) Source: https://github.com/daurnimator/lua-http/blob/master/doc/interfaces/connection.md Completes the connection to the remote server. This function yields until the connection attempt finishes or the timeout is exceeded. ```APIDOC ## connection:connect(timeout) ### Description Completes the connection to the remote server using the address, HTTP version, and options specified during construction. The function yields until the connection attempt finishes or the `timeout` is exceeded. This process may involve DNS lookups, TLS negotiation, and HTTP2 settings exchange. ### Parameters #### Path Parameters - **timeout** (number) - The maximum time to wait for the connection to establish. ### Returns - `true` on success. - `nil`, an error message, and an error number on failure. ``` -------------------------------- ### server:pause() Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.server.md Pauses the server's main loop, preventing it from accepting new client connections until resume() is called. Existing connections are unaffected until they are closed. ```APIDOC ## `server:pause()` ### Description Cause the server loop to stop processing new clients until [*resume*](#http.server:resume) is called. Existing client connections will run until closed. ### Method `server:pause()` ``` -------------------------------- ### server:timeout() Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.server.md Returns the maximum time in seconds to wait before calling server:step(). Used for integrating with external main loops, in conjunction with pollfd() and events(). ```APIDOC ## `server:timeout()` ### Description The maximum time (in seconds) to wait before calling [`server:step()`](#http.server:step). This method is used for integrating with other main loops, and should be used in combination with [`:pollfd()`](#http.server:pollfd) and [`:events()`](#http.server:events). ### Method `server:timeout()` ``` -------------------------------- ### server:events() Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.server.md Returns a string indicating the type of events the server is waiting for (e.g., 'r' for read, 'w' for write). Essential for integrating with external main loops alongside pollfd() and timeout(). ```APIDOC ## `server:events()` ### Description Returns a string indicating the type of events the object is waiting on: the string will contain `"r"` if it wants to be *step*ed when the file descriptor returned by [`pollfd()`](#http.server:pollfd) has had POLLIN indicated; `"w"` for POLLOUT or `"p"` for POLLPRI. This method is used for integrating with other main loops, and should be used in combination with [`:pollfd()`](#http.server:pollfd) and [`:timeout()`](#http.server:timeout). ### Method `server:events()` ``` -------------------------------- ### http.websocket.new_from_uri Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.websocket.md Creates a new http.websocket object of type "client" from the given URI. Optionally accepts a table of protocols to send to the server. ```APIDOC ## http.websocket.new_from_uri(uri, protocols) ### Description Creates a new `http.websocket` object of type `"client"` from the given URI. ### Parameters #### Path Parameters - **uri** (string) - Required - The URI to connect to. - **protocols** (table, optional) - A lua table containing a sequence of protocols to send to the server. ### Returns - `http.websocket` - A new websocket client object. ``` -------------------------------- ### http.h1_connection:get_next_incoming_stream Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h1_connection.md See connection:get_next_incoming_stream(timeout). ```APIDOC ## http.h1_connection:get_next_incoming_stream ### Description See [`connection:get_next_incoming_stream(timeout)`](#connection:get_next_incoming_stream). ### Method `get_next_incoming_stream(timeout)` ### Parameters * **timeout** (number) - The timeout value in seconds. ``` -------------------------------- ### proxies:update Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.proxies.md Updates the proxy configuration by reading environment variables. It supports standard proxy environment variables like http_proxy, https_proxy, all_proxy, and no_proxy. ```APIDOC ## proxies:update ### Description Reads environmental variables that are used to control if requests go through a proxy. Supports `http_proxy`, `https_proxy`, `all_proxy`, and `no_proxy`. ### Method `update(getenv)` ### Parameters #### Query Parameters - `getenv` (function) - Optional - Defaults to `os.getenv`. The function used to retrieve environment variables. ### Returns - `proxies` (object) - The updated proxies object. ``` -------------------------------- ### connection:get_next_incoming_stream(timeout) Source: https://github.com/daurnimator/lua-http/blob/master/doc/interfaces/connection.md Returns the next peer-initiated stream on the connection. ```APIDOC ## connection:get_next_incoming_stream(timeout) ### Description Returns the next peer-initiated stream on the connection. This function can be used to yield and listen for incoming HTTP streams. ### Parameters #### Path Parameters - **timeout** (number) - The maximum time to wait for an incoming stream. ### Returns - The next incoming stream object on success. - `nil` if no stream is received within the timeout period. ``` -------------------------------- ### hpack_context:render_data Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.hpack.md Renders the data currently in the HPACK context's buffer. ```APIDOC ## hpack_context:render_data ### Description Renders the data currently in the HPACK context's buffer. ### Returns - (string) - The rendered data. ``` -------------------------------- ### hpack_context:encode_headers Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.hpack.md Encodes a list of headers into HPACK format. ```APIDOC ## hpack_context:encode_headers ### Description Encodes a list of headers into HPACK format. ### Parameters #### Path Parameters - **headers** (table) - Required - A table of header fields, where each field is a table with 'name' and 'value' keys. ### Returns - (string) - The encoded HPACK data. ``` -------------------------------- ### request:handle_redirect Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.request.md Processes a redirect by taking response headers and returning a new request object configured to fetch from the new location. ```APIDOC ## `request:handle_redirect(headers)` ### Description Process a redirect. `headers` should be response headers for a redirect. Returns a new `request` object that will fetch from new location. ``` -------------------------------- ### http.request:clone Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.request.md Creates and returns a clone of the request object. ```APIDOC ## http.request:clone() ### Description Creates and returns a clone of the request. The clone has its own deep copies of the [`.headers`](#http.request.headers) and [`.h2_settings`](#http.request.h2_settings) fields. The [`.tls`](#http.request.tls) and [`.body`](#http.request.body) fields are shallow copied from the original request. ### Returns - `http.request` - A clone of the original request object. ``` -------------------------------- ### http.h2_connection:connect Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h2_connection.md See connection:connect(timeout). ```APIDOC ## h2_connection:connect(timeout) ### Description See [`connection:connect(timeout)`](#connection:connect) ``` -------------------------------- ### request:go Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.request.md Executes the HTTP request with an optional timeout. The request object can be reused after execution. Returns response headers and a stream on success. ```APIDOC ## `request:go(timeout)` ### Description Performs the request. The request object is **not** invalidated; and can be reused for a new request. On success, returns the response [*headers*](#http.headers) and a [*stream*](#stream). ``` -------------------------------- ### connection:onidle(new_handler) Source: https://github.com/daurnimator/lua-http/blob/master/doc/interfaces/connection.md Provides a callback to be invoked when the connection becomes idle. ```APIDOC ## connection:onidle(new_handler) ### Description Provides a callback function that will be called when the connection becomes idle. A connection is considered idle when there are no requests in progress and no pipelined streams waiting. ### Parameters #### Path Parameters - **new_handler** (function) - The callback function to be executed when the connection becomes idle. The function will receive the `connection` object as its first argument. ### Returns - The previously registered idle handler function. ``` -------------------------------- ### http.h2_connection:settings Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h2_connection.md Manages the connection's HTTP/2 settings. ```APIDOC ## h2_connection:settings(tbl, timeout) ### Description Manages the connection's HTTP/2 settings. ### Parameters - **tbl** (table) - A table containing settings to apply. - **timeout** (number) - The timeout for applying settings. ``` -------------------------------- ### http.cookie.store.store Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.cookie.md Adds a cookie to the store, respecting various constraints. ```APIDOC ## http.cookie.store:store ### Description Attempts to add a cookie to the `store`. ### Parameters - **req_domain** (string) - Required - The domain that the cookie was obtained from. - **req_path** (string) - Required - The path that the cookie was obtained from. - **req_is_http** (boolean) - Required - A boolean flag indicating if the cookie was obtained from a "non-HTTP" API. - **req_is_secure** (boolean) - Required - A boolean flag indicating if the cookie was obtained from a "secure" protocol. - **req_site_for_cookies** (string | nil) - Optional - The host that should be considered as the "site for cookies". - **name** (string) - Required - The name of the cookie. - **value** (string) - Required - The value of the cookie. - **params** (table) - Required - A table where the keys are cookie attribute names and values are cookie attribute values. ### Response - **stored** (boolean) - Returns `true` if the cookie was stored, `false` otherwise. ``` -------------------------------- ### http.h2_connection:checktls Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.h2_connection.md See connection:checktls(). ```APIDOC ## h2_connection:checktls() ### Description See [`connection:checktls()`](#connection:checktls) ``` -------------------------------- ### hpack_context:dynamic_table_tostring Source: https://github.com/daurnimator/lua-http/blob/master/doc/modules/http.hpack.md Returns a string representation of the dynamic table. ```APIDOC ## hpack_context:dynamic_table_tostring ### Description Returns a string representation of the dynamic table. ### Returns - (string) - A string representation of the dynamic table. ```