c3fe6c8e05325fcda0045ffed469feead2127c90
6 #include "http_response.h"
8 struct http_response_s
{
18 http_response_add_data(http_response_t
*response
, const char *data
, int datalen
)
26 newdatasize
= response
->data_size
;
27 while (response
->data_size
+datalen
> newdatasize
) {
30 if (newdatasize
!= response
->data_size
) {
31 response
->data
= realloc(response
->data
, newdatasize
);
32 assert(response
->data
);
34 memcpy(response
->data
+response
->data_length
, data
, datalen
);
35 response
->data_length
+= datalen
;
39 http_response_init(const char *protocol
, int code
, const char *message
)
41 http_response_t
*response
;
44 assert(code
>= 100 && code
< 1000);
46 /* Convert code into string */
47 memset(codestr
, 0, sizeof(codestr
));
48 snprintf(codestr
, sizeof(codestr
), "%u", code
);
50 response
= calloc(1, sizeof(http_response_t
));
55 /* Allocate response data */
56 response
->data_size
= 1024;
57 response
->data
= malloc(response
->data_size
);
58 if (!response
->data
) {
63 /* Add first line of response to the data array */
64 http_response_add_data(response
, protocol
, strlen(protocol
));
65 http_response_add_data(response
, " ", 1);
66 http_response_add_data(response
, codestr
, strlen(codestr
));
67 http_response_add_data(response
, " ", 1);
68 http_response_add_data(response
, message
, strlen(message
));
69 http_response_add_data(response
, "\r\n", 2);
75 http_response_destroy(http_response_t
*response
)
84 http_response_add_header(http_response_t
*response
, const char *name
, const char *value
)
90 http_response_add_data(response
, name
, strlen(name
));
91 http_response_add_data(response
, ": ", 2);
92 http_response_add_data(response
, value
, strlen(value
));
93 http_response_add_data(response
, "\r\n", 2);
97 http_response_finish(http_response_t
*response
, const char *data
, int datalen
)
100 assert(datalen
==0 || (data
&& datalen
> 0));
102 if (data
&& datalen
> 0) {
103 const char *hdrname
= "Content-Length";
106 memset(hdrvalue
, 0, sizeof(hdrvalue
));
107 snprintf(hdrvalue
, sizeof(hdrvalue
)-1, "%d", datalen
);
109 /* Add Content-Length header first */
110 http_response_add_data(response
, hdrname
, strlen(hdrname
));
111 http_response_add_data(response
, ": ", 2);
112 http_response_add_data(response
, hdrvalue
, strlen(hdrvalue
));
113 http_response_add_data(response
, "\r\n\r\n", 4);
115 /* Add data to the end of response */
116 http_response_add_data(response
, data
, datalen
);
118 /* Add extra end of line after headers */
119 http_response_add_data(response
, "\r\n", 2);
121 response
->complete
= 1;
125 http_response_get_data(http_response_t
*response
, int *datalen
)
129 assert(response
->complete
);
131 *datalen
= response
->data_length
;
132 return response
->data
;