add request handler for http request and response generation

This commit is contained in:
Nayan
2025-05-06 16:04:39 -04:00
parent bf8bc98d75
commit d5a8e17f60
4 changed files with 102 additions and 53 deletions

View File

@@ -1,5 +1,7 @@
#include "client_handler.h"
#include "request_handler.h"
#define BUFFER_SIZE 1024
void* client_handler(void* args) {
@@ -11,60 +13,15 @@ void* client_handler(void* args) {
// Null terminate buffer
buffer[bytes_read] = '\0';
// Check if request is GET
char* ptr = buffer; // Modifiable pointer to buffer
char* buf_temp =
(char*)malloc(10); // Temporary buffer to store request code
char* ptr_temp = buf_temp; // Modifiable pointer to temporary buffer
// Copy request code to temporary buffer
while (*ptr != ' ') {
*ptr_temp = *ptr;
ptr++;
ptr_temp++;
}
// Null terminate temporary buffer
*ptr_temp = '\0';
ptr++; // Skip over space
if (strcmp(buf_temp, "GET") == 0) {
printf("Received a GET request!!\n");
} else {
printf("Received a non-GET request!!\n");
return NULL;
}
char* response = (char*)malloc(BUFFER_SIZE);
size_t response_length = BUFFER_SIZE;
// Get filename
char* filename = (char*)malloc(100); // Buffer to store filename
ptr_temp = filename; // Modifiable pointer to filename
*ptr_temp = '.'; // Prepend . to filename
ptr_temp++;
// Copy filename to temporary buffer
while (*ptr != ' ') {
// Convert %20 to space
if (*ptr == '%' && *(ptr + 1) == '2' && *(ptr + 2) == '0') {
ptr += 3;
*ptr_temp = ' ';
ptr_temp++;
} else {
// Copy character
*ptr_temp = *ptr;
ptr++;
ptr_temp++;
}
}
*ptr_temp = '\0'; // Null terminate filename
// Print filename
printf("Filename: %s\n", filename);
handle_request(buffer, bytes_read, response, &response_length);
// Send response
char* response = "HTTP/1.1 200 OK\n\n";
send(client, response, strlen(response), 0);
send(client, response, response_length, 0);
printf("Request:\n");
printf("%s\n", buffer);
free(buf_temp);
free(filename);
free(response);
return NULL;
}
free(buffer);