net.lua (1998B)
1 local M = {} 2 3 --- Makes an HTTP GET request to the given URL (asynchronous). 4 --- 5 --- This function operates in one mode: 6 --- - Asynchronous (non-blocking): Returns immediately and passes the response object to the 7 --- provided `on_response` handler on completion. 8 --- 9 --- @param url string The URL for the request. 10 --- @param opts? table Optional parameters: 11 --- - `verbose` (boolean|nil): Enables verbose output. 12 --- - `retry` (integer|nil): Number of retries on transient failures (default: 3). 13 --- - `outpath` (string|nil): File path to save the response body to. If set, the `body` value in the Response Object will be `true` instead of the response body. 14 --- @param on_response fun(err?: string, response?: { body: string|boolean }) Callback invoked on request 15 --- completion. The `body` field in the response object contains the raw response data (text or binary). 16 --- Called with (err, nil) on failure, or (nil, { body = string|boolean }) on success. 17 function M.request(url, opts, on_response) 18 vim.validate('url', url, 'string') 19 vim.validate('opts', opts, 'table', true) 20 vim.validate('on_response', on_response, 'function') 21 22 opts = opts or {} 23 local retry = opts.retry or 3 24 25 -- Build curl command 26 local args = { 'curl' } 27 if opts.verbose then 28 table.insert(args, '--verbose') 29 else 30 vim.list_extend(args, { '--silent', '--show-error', '--fail' }) 31 end 32 vim.list_extend(args, { '--location', '--retry', tostring(retry) }) 33 34 if opts.outpath then 35 vim.list_extend(args, { '--output', opts.outpath }) 36 end 37 38 table.insert(args, url) 39 40 local function on_exit(res) 41 local s = 'Request failed with exit code %d' 42 local err_msg = res.code ~= 0 43 and ((res.stderr ~= '' and res.stderr) or string.format(s, res.code)) 44 or nil 45 local response = res.code == 0 and { body = opts.outpath and true or res.stdout } or nil 46 47 if on_response then 48 on_response(err_msg, response) 49 end 50 end 51 52 vim.system(args, {}, on_exit) 53 end 54 55 return M