From f299d0fae792383d7bef2f8970118afb5a064696 Mon Sep 17 00:00:00 2001 From: Jonas Widen Date: Sun, 16 Mar 2025 18:34:42 +0100 Subject: [PATCH] Fixed crash --- lua/gemini/api.lua | 103 +++++++++++++++++++++++++++------------------ 1 file changed, 62 insertions(+), 41 deletions(-) diff --git a/lua/gemini/api.lua b/lua/gemini/api.lua index 687d093..f1d4564 100644 --- a/lua/gemini/api.lua +++ b/lua/gemini/api.lua @@ -23,65 +23,86 @@ local function async_request(url, payload, callback) return end - local client = vim.loop.new_tcp() - - client:connect(host, 443, function(err) - if err then + -- Resolve hostname to IP + vim.loop.getaddrinfo(host, "443", { + family = "inet", + socktype = "stream", + protocol = "tcp" + }, function(err, res) + if err then vim.schedule(function() - callback(nil, "Connection error: " .. err) + callback(nil, "DNS resolution error: " .. err) end) return end - local ssl = vim.loop.new_tls() - ssl:wrap(client) + if not res or #res == 0 then + vim.schedule(function() + callback(nil, "Could not resolve hostname") + end) + return + end + + local client = vim.loop.new_tcp() - local request = string.format( - "POST %s HTTP/1.1\r\n" .. - "Host: %s\r\n" .. - "Content-Type: application/json\r\n" .. - "Content-Length: %d\r\n" .. - "\r\n" .. - "%s", - path, host, #payload, payload - ) - - local response = "" - - ssl:write(request, function(err) - if err then + client:connect(res[1].addr, res[1].port, function(err) + if err then vim.schedule(function() - callback(nil, "Write error: " .. err) + callback(nil, "Connection error: " .. err) end) return end + + local ssl = vim.loop.new_tls() + ssl:wrap(client) - ssl:read_start(function(err, chunk) + local request = string.format( + "POST %s HTTP/1.1\r\n" .. + "Host: %s\r\n" .. + "Content-Type: application/json\r\n" .. + "Content-Length: %d\r\n" .. + "\r\n" .. + "%s", + path, host, #payload, payload + ) + + local response = "" + + ssl:write(request, function(err) if err then vim.schedule(function() - callback(nil, "Read error: " .. err) + callback(nil, "Write error: " .. err) end) return end - if chunk then - response = response .. chunk - else - -- Connection closed, process response - local body = response:match("\r\n\r\n(.+)$") - local success, decoded = pcall(vim.json.decode, body) + ssl:read_start(function(err, chunk) + if err then + vim.schedule(function() + callback(nil, "Read error: " .. err) + end) + return + end - vim.schedule(function() - if success then - callback(decoded) - else - callback(nil, "JSON decode error: " .. body) - end - end) - - ssl:close() - client:close() - end + if chunk then + response = response .. chunk + else + -- Connection closed, process response + local body = response:match("\r\n\r\n(.+)$") + 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) + + ssl:close() + client:close() + end + end) end) end) end)