Reference/Native_modules/lu_http_web_requests

LoadModule("lu_http") adds HTTP / HTTPS requests to the server scripts: talk to a website, a Discord webhook, a REST API or your own backend. A request never blocks the server: it runs on a worker thread and your callback is called on the main thread (within a few milliseconds of the answer arriving). Windows uses WinHTTP (system certificates), Linux a built-in client with its own TLS; nothing has to be installed. Up to 4 requests run at once, 256 wait in line; an answer is limited to 16 MB; redirects are followed (5).

Functions

fetch

fetch(url, callback)
fetch(url, method, body, callback)
fetch(url, method, body, headers, callback)
fetch(url, options, callback)

The general call, modelled on the JavaScript one. method is a string ("GET", "POST", "PUT", "DELETE", ...). body is a string (sent as it is), or a table / array (sent as JSON, Content-Type: application/json is added), or null. headers is a string with one Name: value per line, an array of such strings, or a table. options is a table with the keys method, body, headers, timeout (ms), insecure (bool, skip the certificate check) and follow (bool, follow redirects). Build the options with local o = {}; o.method <- "POST"; o.body <- "x=1";. The callback receives one table, the response:

Returns: integer (1; the answer comes to the callback)

http_get

http_get(url, callback)
http_get(url, query, callback)

A GET request. query is a string ("a=1&b=two") or a table of names and values; it is URL-encoded and appended to the address.

Returns: integer

http_post

http_post(url, body, callback)

A POST request. A string body is sent as a form (application/x-www-form-urlencoded); a table or array is sent as JSON.

Returns: integer

GetJson

GetJson(url, callback)
GetJson(url, query, callback)

Like http_get, but the answer is parsed as JSON: the callback is function(data, response), data being the table / array / string / number / bool the server sent, or null when the request failed or the text is not JSON (response.error says why).

Returns: integer

PostJson

PostJson(url, value, callback)

POSTs value (a table, array or string) as JSON and parses the answer like GetJson: function(data, response).

Returns: integer

ParseJson / ToJson

ParseJson(text)
ToJson(value)

ParseJson turns JSON text into tables, arrays, strings, integers, floats, bools and null; it throws a script error on invalid text, so use try { } catch (e) { } for text you do not trust. ToJson goes the other way (tables, arrays, strings, numbers, bools, null). Whole numbers beyond 32 bits become floats.

Returns: value / string

UrlEncode / UrlDecode

UrlEncode(text)
UrlDecode(text)

Percent-encoding for query strings and form bodies.

Returns: string

SetHttpTimeout / SetHttpInsecure / SetHttpUserAgent / HttpPending

SetHttpTimeout(ms)
SetHttpInsecure(bool)
SetHttpUserAgent(text)
HttpPending()

Defaults for the following requests: the timeout (100 - 600000 ms, 15000 by default), skipping the certificate check, and the User-Agent. HttpPending() is the number of requests not delivered yet.

LoadModule("lu_http");

function onPlayerChat(player, text)
{
    if (text == "!ip") {
        local who = player.Name;
        GetJson("https://api.ipify.org?format=json", function(data, r) {
            if (data == null) { print("lookup failed: " + r.error); return; }
            print(who + ": the server's public ip is " + data.ip);
        });
    }
}

// a POST with a JSON body and a header
local body = {}; body.player <- "Alice"; body.score <- 12;
local opt = {};
opt.method <- "POST"; opt.body <- body;
opt.headers <- "Authorization: Bearer abc";
fetch("https://example.org/api/score", opt, function(r) {
    print("score upload: " + r.status + " " + r.error);
});

Example: a Discord webhook. Discord accepts a JSON body with a content field; the answer is empty (status 204) when it worked.

// keep the webhook address in the script, never show it to players
const WEBHOOK = "https://discord.com/api/webhooks/123/abc";

function DiscordSay(text)
{
    local msg = {}; msg.content <- text;
    PostJson(WEBHOOK, msg, function(data, r) {
        if (!r.ok) print("discord: " + r.status + " " + r.error);
    });
}

function onPlayerJoin(player) { DiscordSay(player.Name + " joined the server"); }
NoteThe callback of a request keeps running after its script folder was unloaded with UnloadScript, but a ReloadScripts() abandons requests still in flight (their callbacks never run). Do not send passwords of players to servers you do not control, and never put a server secret into a URL a player can read.

Source code

The full source of lu_http is on the page lu_http source code (download as zip).

Categories: Native modules