Add headers type

This commit is contained in:
Nick Krichevsky 2018-09-01 15:35:19 -04:00
parent 533f695dcb
commit 68f769cf97
2 changed files with 63 additions and 0 deletions

52
common/http_types.c Normal file
View file

@ -0,0 +1,52 @@
#include "http_types.h"
#include <stdlib.h>
#include <string.h>
/**
* Create a new header and append it to the end of the list of existing headers
*
* @param header_name The name of the header
* @param header_contents The contents of the header
* @param existing_header A list of existing headers that this new header should be append to.
* If NULL, no append will take place.
*
* @return The newly created header
*/
struct http_header *insert_header(const char *header_name, const char *header_value, struct http_header *existing_header) {
struct http_header *new_header = malloc(sizeof(struct http_header));
memset(new_header, 0, sizeof(struct http_header));
int name_length = strlen(header_name) + 1;
new_header->name = malloc(name_length * sizeof(char));
strcpy(new_header->name, header_name);
int contents_length = strlen(header_name) + 1;
new_header->value = malloc(contents_length * sizeof(char));
strcpy(new_header->value, header_value);
// If we have an existing header, append it to the end of our list of headers.
if (existing_header != NULL) {
struct http_header *cursor;
// Advance the cursor to the last non-null element
for (cursor = existing_header; cursor->next_header != NULL; cursor = cursor->next_header);
cursor->next_header = new_header;
}
return new_header;
}
/**
* Free all headers in a header list
*
* @param headers The list of headers to free
*/
void free_headers(struct http_header *headers) {
if (headers->next_header != NULL) {
free_headers(headers);
}
free(headers->name);
free(headers->value);
// next_header should have already been freed by recursion
free(headers);
}

View file

@ -6,6 +6,17 @@ struct http_message {
int port;
char *path;
char *contents;
char *start_line;
struct http_header *headers;
};
struct http_header {
char *name;
char *value;
struct http_header *next_header;
};
struct http_header *insert_header(const char *header_name, const char *header_value, struct http_header *existing_header);
void free_headers(struct http_header *headers);
#endif