|
|
|
#include "response.h"
|
|
|
|
|
|
|
|
Response* newResponse(){
|
|
|
|
Response *response = malloc( sizeof( Response ) );
|
|
|
|
memset(response, 0, sizeof(Response));
|
|
|
|
response->headers = malloc( sizeof( HeaderList ) );
|
|
|
|
response->headers->header = newHeader("Content-Length: 0");
|
|
|
|
response->headers->next = NULL;
|
|
|
|
addHeader(response->headers, "Content-Type: text/plain");
|
|
|
|
response->statusCode = 200;
|
|
|
|
response->statusMessage = "OK";
|
|
|
|
response->version = 1.1;
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
|
|
|
char* responseToString( Response *rsp ){
|
|
|
|
// HTTP/x.x xxx OK \r\n
|
|
|
|
int fullLength = 13 + strlen(rsp->statusMessage) + 2 +
|
|
|
|
// Headers \r\n\r\n
|
|
|
|
headerListCharLength(rsp->headers) + 4 + strlen(rsp->body);
|
|
|
|
char retString[fullLength];
|
|
|
|
|
|
|
|
sprintf(retString, "HTTP/%.1f %3d %s\r\n%s\r\n%s", rsp->version, rsp->statusCode,
|
|
|
|
rsp->statusMessage,headersToString(rsp->headers),rsp->body);
|
|
|
|
return strdup(retString);
|
|
|
|
}
|
|
|
|
|
|
|
|
void responseSetBody(Response *rsp, char *string, bool updateContentLength){
|
|
|
|
rsp->body = string;
|
|
|
|
|
|
|
|
|
|
|
|
if ( updateContentLength ){
|
|
|
|
Header *contentLengthHeader = getHeader(rsp->headers, "content-length");
|
|
|
|
char *value = malloc(sizeof(char) * 20);
|
|
|
|
sprintf(value, "%lu", strlen(string) );
|
|
|
|
contentLengthHeader->value = strdup(value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void responseAddHeader(Response *rsp, char header[]){
|
|
|
|
if ( rsp->headers == NULL ){
|
|
|
|
rsp->headers = malloc(sizeof( HeaderList ));
|
|
|
|
rsp->headers->header = newHeader( header );
|
|
|
|
rsp->headers->next = NULL;
|
|
|
|
} else
|
|
|
|
addHeader( rsp->headers, header );
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
Response* newResponseFromSocket(int socket){
|
|
|
|
Response *rsp = newResponse();
|
|
|
|
return rsp;
|
|
|
|
}
|