commit f2c60c4bab49791b5cf26a7c3501372da1b4d882
parent 23c032e55af2b0d8898edb376795340d6aef15c0
Author: Francesco Saccone <francesco@francescosaccone.com>
Date: Tue, 1 Apr 2025 12:01:31 +0200
feat: write response and send to client in all cases
For now, when 404 and 405 error codes occur, some simple
text/plain body is sent. In the future, the program will support
reading <status_code>.html files at root directory.
Signed-off-by: Francesco Saccone <francesco@francescosaccone.com>
Diffstat:
M | main.c | | | 32 | ++++++++++++++++++++++++++++++++ |
1 file changed, 32 insertions(+), 0 deletions(-)
diff --git a/main.c b/main.c
@@ -189,6 +189,7 @@ main(int argc, char *argv[]) {
*file_extension,
*mime_type;
struct http_request *request;
+ struct http_response response;
client_socket_fd = accept_client(server_socket_fd);
@@ -212,6 +213,37 @@ main(int argc, char *argv[]) {
mime_type = get_mime_type_from_extension(file_extension);
file_readable = is_file_readable(normalised_path);
+ if (!file_readable) {
+ response.status = NOT_FOUND;
+ response.content_type = "text/plain";
+ response.body = "404 NOT FOUND";
+ } else {
+ struct file_content file = get_file_content(
+ normalised_path);
+
+ response.status = OK;
+ response.content_type = mime_type;
+ response.body = file.content;
+ }
+
+ switch (request->method) {
+ case GET:
+ send_to_socket(client_socket_fd,
+ compose_http_response_full(response));
+ break;
+ case HEAD:
+ send_to_socket(client_socket_fd,
+ compose_http_response_head(response));
+ break;
+ default:
+ response.status = METHOD_NOT_ALLOWED;
+ response.content_type = "text/plain";
+ response.body = "405 METHOD NOT ALLOWED";
+
+ send_to_socket(client_socket_fd,
+ compose_http_response_full(response));
+ }
+
free(request_buffer);
close_socket(client_socket_fd);
}