-
Notifications
You must be signed in to change notification settings - Fork 4
/
http.lua
85 lines (72 loc) · 1.85 KB
/
http.lua
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
local ce = require("compiler-explorer.lazy")
local json = vim.json
local M = {}
M.get = ce.async.void(function(url)
local data = ce.cache.get()[url]
if data ~= nil then return 200, data end
local args = {
"-X",
"GET",
"-H",
"Accept: application/json",
"-w",
[[\n%{http_code}\n]],
url,
}
local ok, ret = pcall(ce.job.curl, args)
if not ok then error("curl executable not found") end
ce.async.scheduler()
if ret.exit ~= 0 then
error(
("curl error:\ncommand: %s\nexit_code: %d\nstderr: %s"):format(
ret.cmd,
ret.exit,
ret.stderr
)
)
end
if ret.signal == 9 then error("SIGKILL: curl command timed out") end
local split = vim.split(ret.stdout, "\n")
if #split < 2 then
error([[curl response does not follow the <body \n\n status_code> pattern]])
end
local resp, status = json.decode(split[1]), tonumber(split[2])
if status == 200 then ce.cache.get()[url] = resp end
return status, resp
end)
M.post = ce.async.void(function(url, body)
local args = {
"-s",
"-X",
"POST",
"-H",
"Accept: application/json",
"-H",
"Content-Type: application/json",
"-d",
json.encode(body),
"-w",
[[\n%{http_code}\n]],
url,
}
local ok, ret = pcall(ce.job.curl, args)
if not ok then error("curl executable not found") end
ce.async.scheduler()
if ret.exit ~= 0 then
error(
("curl error:\n command: %s \n exit_code %d\n stderr: %s"):format(
ret.cmd,
ret.exit,
ret.stderr
)
)
end
if ret.signal == 9 then error("SIGKILL: curl command timed out") end
local split = vim.split(ret.stdout, "\n")
if #split < 2 then
error([[curl response does not follow the <body \n\n status_code> pattern]])
end
local resp, status = json.decode(split[1]), tonumber(split[2])
return status, resp
end)
return M