Improve loading of HTTP client factories

This introduces a get_http_factory() function which will try to load
a HTTP client library according to the following logic:

1. If the MATRIX_API_HTTP_CLIENT environment variable is defined, it is
   taken as the name of a HTTP client library.
2. Otherwise, if the function paramter is non-nil it is used as the name
   of the HTTP client library to load.
3. Otherwise, the available HTTP client libraries are tried in order,
   and the first one which can be require()'d successfully will be
   used. For now this has only the "chttp" client.
This commit is contained in:
Adrian Perez de Castro
2016-06-28 23:44:20 +03:00
parent cf14c37e58
commit 58ff794d92

View File

@@ -25,6 +25,33 @@ local function get_debug_log_function()
end end
end end
local get_http_factory = function (http_factory)
-- The environment variable has precedence, as it is used to aid debugging.
do
local env_value = os.getenv("MATRIX_API_HTTP_CLIENT")
if env_value and #env_value > 0 then
http_factory = env_value
end
end
-- Try to import supplied HTTP client libraries, in order of preference.
local tries = http_factory and { http_factory } or { "chttp" }
local errors = {}
for i, http_factory in ipairs(tries) do
local ok, factory = pcall(require, "matrix.factory." .. http_factory)
if ok then
get_http_factory = function () return factory end
return get_http_factory()
end
errors[i] = factory
end
local errmsg = { "Could not load any HTTP client library:" }
for i, name in pairs(tries) do
errmsg[#errmsg + 1] = "--- Loading '" .. name .. "'"
errmsg[#errmsg + 1] = errors[i]
end
error(table.concat(errmsg, "\n"))
end
local API = {} local API = {}
API.__name = "matrix.api" API.__name = "matrix.api"
@@ -37,7 +64,7 @@ setmetatable(API, { __call = function (self, base_url, token, http_factory)
txn_id = 0, txn_id = 0,
api_path = "/_matrix/client/r0", -- TODO: De-hardcode api_path = "/_matrix/client/r0", -- TODO: De-hardcode
_log = get_debug_log_function(), _log = get_debug_log_function(),
_http = require("matrix.factory." .. (http_factory or "chttp"))(), _http = get_http_factory(http_factory)(),
}, API) }, API)
end }) end })