refactor: move some stuff, add some docs

This commit is contained in:
Jef Roosens 2023-05-29 12:03:40 +02:00
parent 2fb3e2bb00
commit 9b66223a57
Signed by: Jef Roosens
GPG key ID: B75D4F293C7052DB
2 changed files with 47 additions and 23 deletions

View file

@ -5,26 +5,31 @@
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
static const char *http_response_format = "HTTP/1.1 %i %s\n"
"Content-Length: %lu\n\n";
void http_loop_init_header(http_response *res) {
const char *response_type_name =
http_response_type_names[res->type / 100 - 1][res->type % 100];
// Running snprintf with size 0 prevents it from writing any bytes, while
// still letting it calculate how many bytes it would have written
int buf_size = snprintf(NULL, 0, http_response_format, res->type,
response_type_name, res->body_len);
char *buf = malloc(buf_size + 1);
sprintf(buf, http_response_format, res->type, response_type_name,
res->body_len);
res->head = buf;
res->head_len = buf_size;
}
void http_loop_write_response(event_loop_conn *conn) {
http_response *res = &((http_loop_ctx *)conn->ctx)->res;
// Create head response
if (res->head == NULL) {
const char *response_type_name =
http_response_type_names[res->type / 100 - 1][res->type % 100];
char *format = "HTTP/1.1 %i %s\n"
"Content-Length: %lu\n\n";
// Running snprintf with size 0 prevents it from writing any bytes, while
// still letting it calculate how many bytes it would have written
int buf_size =
snprintf(NULL, 0, format, res->type, response_type_name, res->body_len);
char *buf = malloc(buf_size + 1);
sprintf(buf, format, res->type, response_type_name, res->body_len);
res->head = buf;
res->head_len = buf_size;
http_loop_init_header(res);
}
// The final iteration marks the end of the response, after which we reset the