diff options
| -rw-r--r-- | beaker.h | 1 | ||||
| -rw-r--r-- | src/routing.c | 42 |
2 files changed, 43 insertions, 0 deletions
@@ -96,6 +96,7 @@ char *parse_request_url(const char *request_buffer, UrlParams *params); const char *get_mime_type(const char *file_path); bool serve_static_file(const char *request_path_relative_to_static); bool serve_static_file_with_mime(const char *request_path_relative_to_static, const char *mime_type); +bool serve_data(const char *data, size_t size, const char *mime_type); int beaker_run(const char *ip, int port); diff --git a/src/routing.c b/src/routing.c index b411c0c..98bb531 100644 --- a/src/routing.c +++ b/src/routing.c @@ -331,4 +331,46 @@ bool serve_static_file_with_mime(const char *request_path_relative_to_static, co bool serve_static_file(const char *request_path_relative_to_static) { return serve_static_file_with_mime(request_path_relative_to_static, NULL); +} + +bool serve_data(const char *data, size_t size, const char *mime_type) { + + if (current_client_socket == -1) { + fprintf(stderr, "[ERROR] serve_data: No client socket set. Cannot send data.\n"); + return false; + } + + if (data == NULL || size == 0) { + fprintf(stderr, "[ERROR] serve_data: Invalid data or size.\n"); + return false; + } + + char http_header[BUFFER_SIZE]; + + snprintf(http_header, sizeof(http_header), + "HTTP/1.1 200 OK\r\n" + "Content-Type: %s\r\n" + "Content-Length: %zu\r\n" + "Connection: close\r\n" + "\r\n", + mime_type, size); + + if (send(current_client_socket, http_header, strlen(http_header), 0) < 0) { + perror("Error sending data header"); + fprintf(stderr, "[ERROR] serve_data: Failed to send header.\n"); + return false; + } + + size_t bytes_sent = 0; + while (bytes_sent < size) { + size_t chunk = (size - bytes_sent > BUFFER_SIZE) ? BUFFER_SIZE : (size - bytes_sent); + if (send(current_client_socket, data + bytes_sent, chunk, 0) < 0) { + perror("Error sending data content"); + fprintf(stderr, "[ERROR] serve_data: Failed to send content.\n"); + return false; + } + bytes_sent += chunk; + } + + return true; }
\ No newline at end of file |
