Implement sending binary data

This commit is contained in:
kamkow1
2025-06-20 14:02:31 +02:00
parent d32dd721e1
commit 0fab7bcffe
3 changed files with 31 additions and 5 deletions

16
main.c
View File

@ -80,7 +80,21 @@ void event_handler(struct mg_connection *conn, int ev, void *ev_data)
}
sb_finish(&sb);
mg_http_reply(conn, result->status_code, sb.items, "%s", result->body.items);
if (result->type == ROUTE_RESULT_TEXT) {
mg_http_reply(conn, result->status_code, sb.items, "%s", result->body.items);
} else if (result->type == ROUTE_RESULT_BINARY) {
char *reply = fmt(
"HTTP/1.1 %d OK\r\n"
"%s"
"Content-Length: %zu\r\n"
"\r\n",
result->status_code,
sb.items,
result->body.count
);
mg_printf(conn, "%s", reply);
mg_send(conn, result->body.items, result->body.count);
}
}
}

View File

@ -16,6 +16,7 @@
void make_internal_server_error(Route_Result *result)
{
result->status_code = 500;
result->type = ROUTE_RESULT_TEXT;
list_append(&result->headers, "Content-Type: text/plain");
sb_append_nstr(&result->body, INTERNAL_SERVER_ERROR_MSG);
sb_finish(&result->body);
@ -27,16 +28,22 @@ void make_application_json(Route_Result *result, int code, cJSON *root)
defer { free(root_text); }
result->status_code = code;
result->type = ROUTE_RESULT_TEXT;
list_append(&result->headers, clonestr("Content-Type: application/json"));
sb_append_nstr(&result->body, root_text);
sb_finish(&result->body);
}
void make_image_xicon(Route_Result *result, int code, char *icon)
void make_binary(Route_Result *result, char *content_type, int code, char *data, size_t size)
{
char type[100];
snprintf(type, sizeof(type), "Content-Type: %s", content_type);
result->status_code = code;
list_append(&result->headers, clonestr("Content-Type: image/x-icon"));
sb_append_nstr(&result->body, icon);
result->type = ROUTE_RESULT_BINARY;
list_append(&result->headers, clonestr(type));
for (size_t i = 0; i < size; i++) {
sb_append_char(&result->body, data[i]);
}
sb_finish(&result->body);
}
@ -46,6 +53,7 @@ void make_text(Route_Result *result, char *subtype, int code, char *in)
snprintf(type, sizeof(type), "Content-Type: text/%s", subtype);
result->status_code = code;
result->type = ROUTE_RESULT_TEXT;
list_append(&result->headers, clonestr(type));
sb_append_nstr(&result->body, in);
sb_finish(&result->body);
@ -166,7 +174,7 @@ ROUTE_HANDLER(favicon)
}
sb_finish(&sb);
make_image_xicon(result, 200, sb.items);
make_binary(result, "image/x-icon", 200, sb.items, sb.count);
}
#if MY_DEBUG

View File

@ -5,6 +5,10 @@
#include "mongoose/mongoose.h"
typedef struct {
enum {
ROUTE_RESULT_TEXT,
ROUTE_RESULT_BINARY,
} type;
int status_code;
NString_List headers;
String_Builder body;