add: endpoint responses
This commit is contained in:
parent
5a19e99627
commit
5e64f5963c
18 changed files with 587 additions and 235 deletions
handlers
|
@ -1,9 +1,20 @@
|
|||
#include <string.h>
|
||||
|
||||
#include <constants.h>
|
||||
#include <mongoose.h>
|
||||
#include <logger.h>
|
||||
#include <router.h>
|
||||
#include <handlers.h>
|
||||
|
||||
#define STD_HEADERS "Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Headers: *\r\nAccess-Control-Allow-Methods: *\r\n"
|
||||
#define HEADERS_FMT STD_HEADERS "Content-Type: %s"
|
||||
|
||||
// -2 for "%s" -1 for \0
|
||||
#define HEADERS_FMT_LEN (sizeof(HEADERS_FMT) - 3)
|
||||
|
||||
#define STD_RESPONSE_CONTENT "the server did not create a response"
|
||||
#define STD_RESPONSE_CONTENT_LEN (sizeof(STD_RESPONSE_CONTENT) - 1)
|
||||
|
||||
void
|
||||
handler_connection(struct mg_connection *c, int ev, void *p)
|
||||
{
|
||||
|
@ -18,7 +29,27 @@ handler_connection(struct mg_connection *c, int ev, void *p)
|
|||
{
|
||||
if(endpoint->func)
|
||||
{
|
||||
endpoint->func(c, endpoint->args, p);
|
||||
endpoint_response_t response;
|
||||
response.status_code = 500;
|
||||
response.content_type = "text/plain";
|
||||
response.content_length = STD_RESPONSE_CONTENT_LEN;
|
||||
response.content = STD_RESPONSE_CONTENT;
|
||||
response.alloced_content = false;
|
||||
|
||||
endpoint->func(p, endpoint->args, &response);
|
||||
|
||||
char *response_headers = malloc(sizeof(char) * (HEADERS_FMT_LEN + strlen(response.content_type) + 1));
|
||||
sprintf(response_headers, HEADERS_FMT, response.content_type);
|
||||
|
||||
mg_send_head(c, response.status_code, response.content_length, response_headers);
|
||||
mg_printf(c, "%s", response.content);
|
||||
|
||||
free(response_headers);
|
||||
|
||||
if(response.alloced_content)
|
||||
{
|
||||
free((char*)response.content);
|
||||
}
|
||||
|
||||
for(int i = 0; i < endpoint->args_count; ++i)
|
||||
{
|
||||
|
@ -33,11 +64,7 @@ handler_connection(struct mg_connection *c, int ev, void *p)
|
|||
if(endpoint->method == HTTP_METHOD_OPTIONS)
|
||||
{
|
||||
char options_header[256]; // TODO make more generic
|
||||
sprintf(options_header, "Allow: OPTIONS%s%s%s%s\r\nAccess-Control-Allow-Methods: OPTIONS%s%s%s%s\r\n" STANDARD_HEADERS,
|
||||
endpoint->options & HTTP_METHOD_GET ? ", GET" : "",
|
||||
endpoint->options & HTTP_METHOD_POST ? ", POST" : "",
|
||||
endpoint->options & HTTP_METHOD_PUT ? ", PUT" : "",
|
||||
endpoint->options & HTTP_METHOD_DELETE ? ", DELETE" : "",
|
||||
sprintf(options_header, STD_HEADERS "Allow: OPTIONS%s%s%s%s",
|
||||
endpoint->options & HTTP_METHOD_GET ? ", GET" : "",
|
||||
endpoint->options & HTTP_METHOD_POST ? ", POST" : "",
|
||||
endpoint->options & HTTP_METHOD_PUT ? ", PUT" : "",
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue