add add header function

This commit is contained in:
Nayan
2025-05-07 18:38:36 -04:00
parent 77a7fa11c8
commit 70d930c89f
2 changed files with 48 additions and 0 deletions

View File

@@ -118,3 +118,19 @@ char* get_header_value_request(http_request* req, char* key) {
} }
return NULL; 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));
}

View File

@@ -2,6 +2,7 @@
#define HTTP_STUFF_H #define HTTP_STUFF_H
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h> #include <string.h>
#include <sys/types.h> #include <sys/types.h>
@@ -141,4 +142,35 @@ char* reponse_to_string(http_response* res);
*/ */
char* get_header_value_request(http_request* req, char* key); 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 #endif