For learning purpose, I am trying to make an HTTP Server in C. What did I do wrong here that I get r->body is null
request_t *parse_request(char *buf) {
request_t *req = malloc(sizeof(request_t));
char *save_prt;
char *line = strtok_r(buf, "\r\n", &save_prt);
char **parts = malloc(sizeof(char *) * 3);
request_line_t *req_line = malloc(sizeof(request_line_t));
str_split(line, " ", parts);
req_line->method = parts[0];
req_line->path = parts[1];
req_line->version = parts[2];
req->line = req_line;
free(parts);
header_map_t *headers = new_header_map();
char *header_line;
while ((header_line = strtok_r(NULL, "\r\n", &save_prt)) != NULL) {
char **header_parts = malloc(sizeof(char *) * 2);
str_split(header_line, ":", header_parts);
char *val = trim(header_parts[1]);
add_header(headers, header_parts[0], val);
free(header_parts);
}
req->headers = headers;
char *content_length_header = get_header(headers, "Content-Length");
if (content_length_header != NULL) {
int content_length = atoi(content_length_header);
if (content_length > 1) {
req->body = malloc(sizeof(char) * 1024);
char *body = strtok_r(NULL, "\r\n", &save_prt);
printf("body: %s \n", body);
req->body = body;
}
}
return req;
}
int main() {
char buf[1024] = "POST /files/number HTTP/1.1\r\n"
"Host: localhost:4221\r\n"
"User-Agent: curl/7.64.1\r\n"
"Accept: */*\r\n"
"Content-Type: application/octet-stream\r\n"
"Content-Length: 5\r\n"
"\r\n"
"12345";
request_t *r = parse_request(buf);
if (r->body != NULL) {
printf("%s\n", r->body);
}
return 0;
}
Expected r->body to be 12345, but getting null