commit ed1edf7a92178db38a2113f7e18c1f47b2dae0a2
parent 85b7f640c2dd0625d49d27e880abedcc6b18a52d
Author: Francesco Saccone <francesco@francescosaccone.com>
Date: Mon, 31 Mar 2025 20:03:52 +0200
refactor: divide compose_http_response in ..._head and ..._full
That is to easily generate the raw responses for GET and HEAD
requests respectively.
Signed-off-by: Francesco Saccone <francesco@francescosaccone.com>
Diffstat:
M | http.c | | | 39 | ++++++++++++++++++++++++++++++++------- |
M | http.h | | | 11 | +++++++++-- |
2 files changed, 41 insertions(+), 9 deletions(-)
diff --git a/http.c b/http.c
@@ -48,14 +48,12 @@ get_length_of_integer(unsigned int integer) {
}
char *
-compose_http_response(struct http_response response) {
+compose_http_response_head(struct http_response response) {
size_t size;
unsigned int status_code = status_map[response.status].code;
const char *template = "HTTP/1.1 %u %s\r\n"
"Content-Type: %s; charset=UTF-8\r\n"
- "Content-Length: %u\r\n"
- "\r\n"
- "%s\n",
+ "Content-Length: %u\r\n",
*status_message = status_map[response.status].message,
*content_type = response.content_type,
*body = response.body;
@@ -72,8 +70,7 @@ compose_http_response(struct http_response response) {
+ get_length_of_integer(status_code)
+ strlen(status_message)
+ strlen(content_type)
- + get_length_of_integer(strlen(body))
- + strlen(body);
+ + get_length_of_integer(strlen(body));
buffer = malloc(size);
@@ -81,7 +78,35 @@ compose_http_response(struct http_response response) {
status_code,
status_message,
content_type,
- strlen(body),
+ strlen(body));
+
+ buffer[size] = '\0';
+
+ return buffer;
+}
+
+char *
+compose_http_response_full(struct http_response response) {
+ size_t size;
+ const char *template = "%s"
+ "\r\n"
+ "%s\n",
+ *head = compose_http_response_head(response),
+ *body = response.body;
+ char *buffer;
+
+ /*
+ * Read the comment inside the compose_http_response_head function in this
+ * same file.
+ */
+ size = strlen(template)
+ + strlen(head)
+ + strlen(body);
+
+ buffer = malloc(size);
+
+ snprintf(buffer, size, template,
+ head,
body);
buffer[size] = '\0';
diff --git a/http.h b/http.h
@@ -84,9 +84,16 @@ struct http_request *
parse_http_request(char *request);
/*
- * Returns the raw HTTP response from a given a http_response.
+ * Returns the head of the raw HTTP response from a given a http_response.
*/
char *
-compose_http_response(struct http_response response);
+compose_http_response_head(struct http_response response);
+
+/*
+ * Returns the raw HTTP response, composed of both head and body, from a
+ * given a http_response.
+ */
+char *
+compose_http_response_full(struct http_response response);
#endif