From 338736f6cd60bf634ef04ab246187caa78597789 Mon Sep 17 00:00:00 2001 From: Aki Date: Sun, 16 Aug 2020 21:04:26 +0200 Subject: Added data to lua response --- default.lua | 4 +++- response.c | 30 ++++++++++++++++++++++++++---- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/default.lua b/default.lua index d3a0c61..95ba609 100644 --- a/default.lua +++ b/default.lua @@ -1,5 +1,7 @@ --- Default client request handler. -- TODO: Add documentation once request and response API are more stable. return function (method, path, version, headers, data) - return [["Hello from plop/lua!"]] + local response_data = [["Hello from plop/lua!"]] + local headers = {Connection="close", ["Content-Length"]=#response_data, ["Content-Type"]="application/json"} + return {status=200, headers=headers, data=response_data} end diff --git a/response.c b/response.c index 5f5cec7..02dd59b 100644 --- a/response.c +++ b/response.c @@ -1,5 +1,6 @@ #include "response.h" +#include #include #include #include @@ -100,11 +101,32 @@ int response_send(lua_State * L, const int fd) buffer[bytes_used + 1] = '\n'; bytes_used += 2; - // TODO: Add data write + lua_pushstring(L, "data"); + lua_gettable(L, -2); + size_t data_length = 0; + const char * data = lua_tolstring(L, -1, &data_length); - int result = write(fd, buffer, bytes_used ); - free(buffer); - lua_pop(L, 1); + if (NULL != data && 0 < data_length) + { + // TODO: There are quite a few parts which could be moved out of this function. + if (bytes_total < bytes_used + (int) data_length) + { + bytes_total += data_length; + buffer = realloc(buffer, bytes_total); + if (NULL == buffer) + { + lua_pop(L, 2); + return write(fd, error_response, strlen(error_response)); + } + } + + memcpy(buffer + bytes_used, data, data_length); + bytes_used += data_length; + } + + int result = write(fd, buffer, bytes_used); + free(buffer); // TODO: Don't free the buffer if EAGAIN or EWOULDBLOCK, so it can be reused. + lua_pop(L, 2); return result; } -- cgit v1.1