summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorAki <please@ignore.pl>2020-08-16 21:04:26 +0200
committerAki <please@ignore.pl>2020-08-16 21:04:26 +0200
commit338736f6cd60bf634ef04ab246187caa78597789 (patch)
treef81f059484995f8c16458a7cbf1d3863b7ae20c8
parent192cea2f12cec425320e92865b0103ea42ffd4ba (diff)
downloadplop-338736f6cd60bf634ef04ab246187caa78597789.zip
plop-338736f6cd60bf634ef04ab246187caa78597789.tar.gz
plop-338736f6cd60bf634ef04ab246187caa78597789.tar.bz2
Added data to lua response
-rw-r--r--default.lua4
-rw-r--r--response.c30
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 <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -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;
}