diff --git a/Capy64/Assets/Lua/boot/04_http.lua b/Capy64/Assets/Lua/boot/04_http.lua new file mode 100644 index 0000000..ffea64a --- /dev/null +++ b/Capy64/Assets/Lua/boot/04_http.lua @@ -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 \ No newline at end of file diff --git a/Capy64/LuaRuntime/Libraries/HTTP.cs b/Capy64/LuaRuntime/Libraries/HTTP.cs index d282752..efb6e19 100644 --- a/Capy64/LuaRuntime/Libraries/HTTP.cs +++ b/Capy64/LuaRuntime/Libraries/HTTP.cs @@ -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);