-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHTTPResponse.cpp
90 lines (73 loc) · 2.24 KB
/
HTTPResponse.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <vector>
#include "HTTPLib.h"
#define ENDLINE "\r\n\r\n"
namespace HttpLib{
const std::string HTTPResponse::TYPE_HTML = "text/html";
const std::string HTTPResponse::TYPE_TEXT = "text/plain";
const std::string HTTPResponse::TYPE_CSS = "text/css";
const std::string HTTPResponse::TYPE_JAVASCRIPT = "application/javascript";
const std::string HTTPResponse::TYPE_JSON = "application/json";
const std::string HTTPResponse::TYPE_ZIP = "application/zip";
const std::string HTTPResponse::TYPE_PDF = "application/pdf";
const std::string HTTPResponse::TYPE_XML = "application/xml";
const std::string HTTPResponse::TYPE_MPEG = "audio/mpeg";
const std::string HTTPResponse::TYPE_VORBIS = "audio/vorbis";
const std::string HTTPResponse::TYPE_PNG = "image/png";
const std::string HTTPResponse::TYPE_JPEG = "image/jpeg";
const std::string HTTPResponse::TYPE_GIF = "image/gif";
HTTPResponse::HTTPResponse()
{
contentType = TYPE_HTML;
m_HeaderSent = false;
}
HTTPResponse::~HTTPResponse()
{
this->flush();
// To prevent browser from returning error 500 for empty responses
if(!m_HeaderSent){
std::cout << TYPE_TEXT << ENDLINE;
}
}
void HTTPResponse::header(std::string str)
{
if(m_HeaderSent){
std::cout << "Headers already sent" << std::endl;
return;
}
std::cout << str << ENDLINE;
m_HeaderSent = true;
}
void HTTPResponse::redirect(std::string url)
{
if(m_HeaderSent){
std::cout << "Headers already sent" << std::endl;
return;
}
std::cout << "Location: " << url << ENDLINE;
m_HeaderSent = true;
}
void HTTPResponse::flush()
{
if(response.size() > 0){
if(m_HeaderSent){
std::cout << "Headers already sent" << std::endl;
return;
}
std::cout << "Content-Type: " << contentType << ENDLINE;
for(std::vector<std::string>::iterator it = response.begin();it != response.end();++it){
std::cout << *it;
}
m_HeaderSent = true;
response.clear();
}
}
void HTTPResponse::setContentType(std::string str)
{
contentType = str;
}
void HTTPResponse::write(std::string str)
{
response.push_back(str);
}
};