You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.5 KiB
57 lines
1.5 KiB
1 year ago
|
local uv = vim.loop
|
||
|
|
||
|
local function parse_headers(lines)
|
||
|
local headers = {}
|
||
|
for _, line in ipairs(lines) do
|
||
|
local key, value = line:match("^(.-):%s*(.*)$")
|
||
|
if key then
|
||
|
headers[key:lower()] = value
|
||
|
end
|
||
|
end
|
||
|
return headers
|
||
|
end
|
||
|
|
||
|
local function make_request(url, method, headers, payload)
|
||
|
local parts = vim.split(url, "/")
|
||
|
local host = parts[3]
|
||
|
local path = "/" .. table.concat(parts, "/", 4)
|
||
|
|
||
|
local tcp = uv.new_tcp()
|
||
|
local results = {}
|
||
|
|
||
|
tcp:connect(host, 7700, function(err)
|
||
|
assert(not err, err)
|
||
|
tcp:write(method .. " " .. path .. " HTTP/1.1\r\n" ..
|
||
|
"Host: " .. host .. "\r\n" ..
|
||
|
table.concat(headers, "\r\n") ..
|
||
|
"\r\n\r\n" .. payload,
|
||
|
function(write_err)
|
||
|
assert(not write_err, write_err)
|
||
|
tcp:read_start(function(read_err, chunk)
|
||
|
assert(not read_err, read_err)
|
||
|
if chunk then
|
||
|
table.insert(results, chunk)
|
||
|
else
|
||
|
tcp:read_stop()
|
||
|
tcp:close()
|
||
|
end
|
||
|
end)
|
||
|
end)
|
||
|
end)
|
||
|
|
||
|
uv.run()
|
||
|
|
||
|
local raw_response = table.concat(results)
|
||
|
local _, header_end = raw_response:find("\r\n\r\n")
|
||
|
local raw_headers = raw_response:sub(1, header_end)
|
||
|
local body = raw_response:sub(header_end + 1)
|
||
|
local headers = parse_headers(vim.split(raw_headers, "\r\n"))
|
||
|
|
||
|
return headers, body
|
||
|
end
|
||
|
|
||
|
return {
|
||
|
make_request = make_request
|
||
|
}
|
||
|
|