Added HTTP extensions, http.requestAsync returns a response table

This commit is contained in:
Alessandro Proto 2023-01-12 22:10:51 +01:00
parent b7574af812
commit 84401bc12a
2 changed files with 55 additions and 6 deletions

View file

@ -0,0 +1,19 @@
local http = require("http")
local event = require("event")
function http.request(url, body, headers, options)
local requestId = http.requestAsync(url, body, headers, options)
local _, response
repeat
_, id, response = event.pull("http_response")
until id == requestId
return response
end
function http.get(url, headers, options)
return http.request(url, nil, headers, options)
end
function http.post(url, body, headers, options)
return http.request(url, body, headers, options)
end

View file

@ -1,7 +1,9 @@
using Capy64.API;
using Capy64.LuaRuntime.Extensions;
using KeraLua;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
namespace Capy64.LuaRuntime.Libraries;
@ -16,7 +18,7 @@ public class HTTP : IPlugin
{
new()
{
name = "request",
name = "requestAsync",
function = L_Request,
},
new()
@ -155,22 +157,50 @@ public class HTTP : IPlugin
else
content = await response.Content.ReadAsStringAsync();
// wip
/*
_game.LuaRuntime.PushEvent("http_response", L =>
{
// arg 1, request id
L.PushInteger(requestId);
// arg 2, response data
L.NewTable();
L.PushString("success");
L.PushBoolean(response.IsSuccessStatusCode);
L.SetTable(-3);
return 2;
});*/
L.PushString("statusCode");
L.PushNumber((int)response.StatusCode);
L.SetTable(-3);
_game.LuaRuntime.PushEvent("http_response", requestId, response.IsSuccessStatusCode, content, (int)response.StatusCode, response.ReasonPhrase);
L.PushString("reasonPhrase");
L.PushString(response.ReasonPhrase);
L.SetTable(-3);
L.PushString("content");
if ((bool)options["binary"])
L.PushBuffer((byte[])content);
else
L.PushString((string)content);
L.SetTable(-3);
L.PushString("headers");
L.NewTable();
foreach(var header in response.Headers)
{
L.PushString(header.Key);
L.PushArray(header.Value.ToArray());
L.SetTable(-3);
}
L.SetTable(-3);
return 2;
});
//_game.LuaRuntime.PushEvent("http_response", requestId, response.IsSuccessStatusCode, content, (int)response.StatusCode, response.ReasonPhrase);
});
L.PushInteger(requestId);