Fixed crash

This commit is contained in:
Jonas Widen 2025-03-16 18:38:31 +01:00
parent cc5b5f4e13
commit 05906e65ba

View File

@ -12,22 +12,15 @@ end
-- Async HTTP request function
local function async_request(url, payload, callback)
-- Create a temporary file for the response
local temp_file = vim.fn.tempname()
-- Construct curl command
local curl_cmd = string.format(
'curl -s -X POST -H "Content-Type: application/json" -d %s %s',
vim.fn.shellescape(payload),
vim.fn.shellescape(url)
)
local response = ""
local error_msg = ""
-- Create job
-- Create pipes for stdout and stderr
local stdout = vim.loop.new_pipe()
local stderr = vim.loop.new_pipe()
local handle
handle = vim.loop.spawn('curl', {
-- Spawn curl process
local handle = vim.loop.spawn('curl', {
args = {
'-s',
'-X', 'POST',
@ -36,51 +29,15 @@ local function async_request(url, payload, callback)
url
},
stdio = {nil, stdout, stderr}
}, function(code)
}, function(exit_code, signal) -- This is the exit callback
-- Close all handles
stdout:close()
stderr:close()
handle:close()
end)
if not handle then
vim.schedule(function()
callback(nil, "Failed to start curl")
end)
return
end
local response = ""
local error_msg = ""
stdout:read_start(function(err, chunk)
if err then
if exit_code ~= 0 then
vim.schedule(function()
callback(nil, "Read error: " .. err)
end)
return
end
if chunk then
response = response .. chunk
end
end)
stderr:read_start(function(err, chunk)
if err then
vim.schedule(function()
callback(nil, "Error reading stderr: " .. err)
end)
return
end
if chunk then
error_msg = error_msg .. chunk
end
end)
-- When everything is done
handle:on('exit', function(code)
if code ~= 0 then
vim.schedule(function()
callback(nil, "Curl failed: " .. error_msg)
callback(nil, "Curl failed with code " .. exit_code .. ": " .. error_msg)
end)
return
end
@ -95,6 +52,39 @@ local function async_request(url, payload, callback)
end
end)
end)
if not handle then
vim.schedule(function()
callback(nil, "Failed to start curl")
end)
return
end
-- Handle stdout data
stdout:read_start(function(err, chunk)
if err then
vim.schedule(function()
callback(nil, "Read error: " .. err)
end)
return
end
if chunk then
response = response .. chunk
end
end)
-- Handle stderr data
stderr:read_start(function(err, chunk)
if err then
vim.schedule(function()
callback(nil, "Error reading stderr: " .. err)
end)
return
end
if chunk then
error_msg = error_msg .. chunk
end
end)
end
function M.get_response(prompt, context, callback)