aboutsummaryrefslogtreecommitdiffstats
path: root/utils/curl.lua
blob: 532d0bd6609de04d95100030bdef334515b55a11 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
local mp = require('mp')
local utils = require('mp.utils')
local msg = require('mp.msg')

local M = {}

--- run a curl request
---@param cmd table list of curl args
---@param method? string
---@return table? json, number? httpcode
function M.request(cmd, method)
  if type(cmd) == "string" then
    cmd = { cmd }
  end

  table.insert(cmd, 1, '%{http_code}')
  table.insert(cmd, 1, "-w")
  if method then
    table.insert(cmd, 1, method)
    table.insert(cmd, 1, "-X")
  end
  table.insert(cmd, 1, "curl")

  local r = mp.command_native({
    name = "subprocess",
    capture_stdout = true,
    capture_stderr = true,
    playback_only = false,
    args = cmd
  })

  local json, err, code = utils.parse_json(r.stdout, true)
  if not json then
    msg.error(string.format("failed to parse json: %s", err))
    return
  end

  return json, tonumber(code)
end

return M