From c532849cbfcd749d11905ac05a9b1aeedb44a3e2 Mon Sep 17 00:00:00 2001 From: Jonas Widen Date: Sun, 16 Mar 2025 19:04:32 +0100 Subject: [PATCH] Get rid of curl --- lua/gemini/http.lua | 82 +++++++++++---------------------------------- 1 file changed, 20 insertions(+), 62 deletions(-) diff --git a/lua/gemini/http.lua b/lua/gemini/http.lua index f0a4a7d..01b0f00 100644 --- a/lua/gemini/http.lua +++ b/lua/gemini/http.lua @@ -8,85 +8,43 @@ function Request.new(url, payload) local self = setmetatable({}, Request) self.url = url self.payload = payload - self.response = "" - self.error_msg = "" - self.stdout = vim.loop.new_pipe() - self.stderr = vim.loop.new_pipe() - self.handle = nil return self end -function Request:cleanup() - if self.stdout then self.stdout:close() end - if self.stderr then self.stderr:close() end - if self.handle then self.handle:close() end -end - -function Request:handle_error(callback, msg) - self:cleanup() - vim.schedule(function() - callback(nil, msg) - end) -end - -function Request:setup_pipes(callback) - self.stdout:read_start(function(err, chunk) - if err then - self:handle_error(callback, "Read error: " .. err) - return - end - if chunk then - self.response = self.response .. chunk - end - end) - - self.stderr:read_start(function(err, chunk) - if err then - self:handle_error(callback, "Error reading stderr: " .. err) - return - end - if chunk then - self.error_msg = self.error_msg .. chunk - end - end) -end - function Request:execute(callback) - self.handle = vim.loop.spawn('curl', { - args = { - '-s', - '-X', 'POST', - '-H', 'Content-Type: application/json', - '-d', self.payload, - self.url - }, - stdio = {nil, self.stdout, self.stderr} - }, function(exit_code) - self:cleanup() + local headers = { + ['Content-Type'] = 'application/json', + } - if exit_code ~= 0 then + vim.loop.http_request({ + url = self.url, + method = 'POST', + headers = headers, + body = self.payload + }, function(err, response) + if err then vim.schedule(function() - callback(nil, "Curl failed with code " .. exit_code .. ": " .. self.error_msg) + callback(nil, "HTTP request failed: " .. err) end) return end - local success, decoded = pcall(vim.json.decode, self.response) + if response.status ~= 200 then + vim.schedule(function() + callback(nil, "HTTP request failed with status " .. response.status) + end) + return + end + + local success, decoded = pcall(vim.json.decode, response.body) vim.schedule(function() if success then callback(decoded) else - callback(nil, "JSON decode error: " .. self.response) + callback(nil, "JSON decode error: " .. response.body) end end) end) - - if not self.handle then - self:handle_error(callback, "Failed to start curl") - return - end - - self:setup_pipes(callback) end M.Request = Request