Lua curl-backed JSON GET with hard timeout
Lua
local function http_json(url, opts)
opts = opts or {}
local timeout = opts.timeout or 5
local cmd = ('curl -fsS --max-time %d -H %q %q'):format(timeout, 'Accept: application/json', url)
local pipe = assert(io.popen(cmd, 'r'))
local body = pipe:read('a')
local ok, why, code = pipe:close()
if not ok then return nil, ('request failed: %s %s'):format(why, tostring(code)) end
local decode = opts.decode
if not decode then return nil, 'opts.decode JSON decoder is required' end
local decoded, parsed = pcall(decode, body)
if not decoded then return nil, 'invalid JSON: ' .. tostring(parsed) end
return parsed
end
return http_json