diff --git a/lua/gemini/http.lua b/lua/gemini/http.lua index 01b0f00..9310c46 100644 --- a/lua/gemini/http.lua +++ b/lua/gemini/http.lua @@ -12,36 +12,63 @@ function Request.new(url, payload) end function Request:execute(callback) - local headers = { - ['Content-Type'] = 'application/json', - } + local client = vim.uv.new_tcp() + local headers = table.concat({ + string.format("POST %s HTTP/1.1", self.url), + "Host: generativelanguage.googleapis.com", + "Content-Type: application/json", + string.format("Content-Length: %d", #self.payload), + "Connection: close", + "", + self.payload + }, "\r\n") - vim.loop.http_request({ - url = self.url, - method = 'POST', - headers = headers, - body = self.payload - }, function(err, response) + local response_data = "" + + client:connect("generativelanguage.googleapis.com", 443, function(err) if err then vim.schedule(function() - callback(nil, "HTTP request failed: " .. err) + callback(nil, "Connection failed: " .. err) end) + client:close() return end - if response.status ~= 200 then - vim.schedule(function() - callback(nil, "HTTP request failed with status " .. response.status) - end) - return - end + client:write(headers) + + client:read_start(function(err, chunk) + if err then + vim.schedule(function() + callback(nil, "Read error: " .. err) + end) + client:close() + return + end - local success, decoded = pcall(vim.json.decode, response.body) - vim.schedule(function() - if success then - callback(decoded) + if chunk then + response_data = response_data .. chunk else - callback(nil, "JSON decode error: " .. response.body) + -- End of response + client:close() + + -- Parse response + local headers_end = response_data:find("\r\n\r\n") + if headers_end then + local body = response_data:sub(headers_end + 4) + local success, decoded = pcall(vim.json.decode, body) + + vim.schedule(function() + if success then + callback(decoded) + else + callback(nil, "JSON decode error: " .. body) + end + end) + else + vim.schedule(function() + callback(nil, "Invalid response format") + end) + end end end) end)