C and C++ web framework. http://rapida.vilor.one/docs
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
2.5 KiB

/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright 2022 Ivan Polyakov */
#include "response.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static size_t calc_res_status_sz(const rpd_res *res);
static size_t calc_res_headers_sz(const rpd_keyval *res);
void rpd_res_init(rpd_res *dest)
{
dest->status = rpd_res_st_ok;
dest->body = NULL;
rpd_keyval_init(&dest->headers, 5);
dest->headers.unique = 0;
}
2 years ago
int rpd_res_headers_str(char **dest, const rpd_res *src)
{
size_t size, i = 0;
2 years ago
char *ptr;
size = calc_res_headers_sz(&src->headers);
2 years ago
*dest = (char *) malloc(sizeof(char) * size);
if (!*dest) {
perror("malloc");
return 1;
}
ptr = *dest;
while (i < src->headers.size) {
ptr += sprintf(
ptr,
"%s: %s\r\n",
src->headers.items[i].key,
src->headers.items[i].val);
i++;
2 years ago
}
return 0;
}
int rpd_res_str(char **dest, const rpd_res *res)
{
2 years ago
size_t headers_size, size;
char *ptr, *headers;
size = headers_size = calc_res_headers_sz(&res->headers);
size += calc_res_status_sz(res);
2 years ago
if (res->body)
size += 2 + strlen(res->body);
*dest = (char *) malloc(sizeof(char) * size);
if (!*dest) {
2 years ago
perror("malloc");
return 1;
}
/* header */
2 years ago
ptr = *dest;
ptr += sprintf(ptr, "Status: %d\r\n", res->status);
2 years ago
if (rpd_res_headers_str(&headers, res)) {
return 1;
}
2 years ago
memcpy(ptr, headers, headers_size);
free(headers);
ptr += headers_size;
memcpy(ptr, "\r\n", 2);
ptr += 2;
/* body */
if (res->body) {
int bodylen = strlen(res->body);
memcpy(ptr, res->body, bodylen);
ptr += bodylen;
}
return 0;
}
static size_t calc_res_status_sz(const rpd_res *res)
{
2 years ago
size_t size = 0;
size += strlen("Status: \r\n");
size += 3; /* plus status code */
return size;
}
static size_t calc_res_headers_sz(const rpd_keyval *headers)
{
size_t size = 0, i = 0;
while (i < headers->size) {
size += strlen(headers->items[i].key);
size += 2; /* plus ": " */
size += strlen(headers->items[i].val);
size += 2; /* plus CRLF */
i++;
}
return size;
}
void rpd_res_cleanup(rpd_res *res)
{
res->status = rpd_res_st_ok;
if (res->body) {
free(res->body);
res->body = NULL;
}
if (res->headers.capacity) {
rpd_keyval_cleanup(&res->headers);
}
}