Dev:URL API

You can do web requests from a module, for example a HTTPS callout to receive some JSON.

Below we explain how to do this. Behind the scenes UnrealIRCd keeps things safe, even if the server is REHASHed between starting the request and receiving the response (and your module is reloaded).

Registering your callback
In your MOD_INIT use RegisterApiCallback to register your response handler: /* Forward declaration */ void my_download_complete(OutgoingWebRequest *request, OutgoingWebResponse *response);

MOD_INIT { [..]       RegisterApiCallback(modinfo->handle, API_CALLBACK_WEB_RESPONSE, "my_download_complete", my_download_complete); return MOD_SUCCESS; }

Doing the web request
Create an OutgoingWebRequest struct and then fill in members. You must set ->apicallback to the name of the api callback that you registered in MOD_INIT above.

Example: OutgoingWebRequest *w = safe_alloc(sizeof(OutgoingWebRequest)); safe_strdup(w->url, cfg.url); w->http_method = HTTP_METHOD_GET; safe_strdup(w->apicallback, "cbl_download_complete"); // you can set more fields in w->... like callback_data, see OutgoingWebRequest definition in source in modules.h. url_start_async(w);

Receiving the web response
Here is where your my_download_complete comes into play.

In this example we expect to receive a JSON response, which we try to parse:

void my_download_complete(OutgoingWebRequest *request, OutgoingWebResponse *response) {   json_t *result; json_error_t jerr;

if (response->errorbuf || !response->memory) {       unreal_log(ULOG_INFO, "mymod", "MYMOD_BAD_RESPONSE", NULL,                   "Error while trying to check $url: $error",                   log_data_string("url", request->url),                   log_data_string("error", response->errorbuf ? response->errorbuf : "No data (body) returned")); return; }

result = json_loads(response->memory, JSON_REJECT_DUPLICATES, &jerr); if (!result) {       unreal_log(ULOG_INFO, "mymod", "MYMOD_BAD_RESPONSE", NULL,                   "Error while trying to check $url: JSON parse error",                   log_data_string("url", request->url)); return; }

// Now do something useful with the json in 'result'

// Finally, free 'result' and return json_decref(result); }