diff --git a/http_stuff.c b/http_stuff.c index ab235e1..8de6e98 100644 --- a/http_stuff.c +++ b/http_stuff.c @@ -117,4 +117,20 @@ char* get_header_value_request(http_request* req, char* key) { } } return NULL; +} + +void request_add_header_n(http_request* req, char* key, size_t key_length, + char* value, size_t value_length) { + req->num_headers++; + req->headers = realloc(req->headers, req->num_headers * sizeof(header_kv)); + req->headers[req->num_headers - 1].key = malloc(key_length + 1); + req->headers[req->num_headers - 1].value = malloc(value_length + 1); + memcpy(req->headers[req->num_headers - 1].key, key, key_length); + memcpy(req->headers[req->num_headers - 1].value, value, value_length); + req->headers[req->num_headers - 1].key[key_length] = '\0'; + req->headers[req->num_headers - 1].value[value_length] = '\0'; +} + +void request_add_header(http_request* req, char* key, char* value) { + request_add_header_n(req, key, strlen(key), value, strlen(value)); } \ No newline at end of file diff --git a/http_stuff.h b/http_stuff.h index 1d1e56f..239fbf3 100644 --- a/http_stuff.h +++ b/http_stuff.h @@ -2,6 +2,7 @@ #define HTTP_STUFF_H #include +#include #include #include @@ -141,4 +142,35 @@ char* reponse_to_string(http_response* res); */ char* get_header_value_request(http_request* req, char* key); +/** + * Adds a new header to an http_request struct with the given key and value. + * + * @param req The request to add the header to + * @param key The key of the header + * @param key_length The length of the key + * @param value The value of the header + * @param value_length The length of the value + * + * @details + * This function is meant to be used when the lengths of the key and value are + * already known. It is more efficient than request_add_header, which calls + * strlen to get the lengths of the key and value. + */ +void request_add_header_n(http_request* req, char* key, size_t key_length, + char* value, size_t value_length); + +/** + * Adds a header to the given HTTP request. + * + * @param req The request to add the header to + * @param key The key of the header to add + * @param value The value of the header to add + * + * @details + * This is a convenience function for request_add_headern. It will add a header + * with the given key and value to the given request. It will automatically + * calculate the length of the key and value. + */ +void request_add_header(http_request* req, char* key, char* value); + #endif \ No newline at end of file