目录
类功能
类定义
// HttpResponse响应模块功能设计
class HttpResponse
{
private:
int _statu;
bool _redirect_flag; // 重定向标志
std::string _body;
std::string _redirect_url; // 重定向地址
std::unordered_map<std::string, std::string> _headers;
public:
void ReSet(); // 重置
void SetHeader(std::string &key, std::string &val);
bool HasHeader(std::string &key);
std::string GetHeader(std::string &key);
void SetContent(std::string &body, std::string &type);
void SetRedirect(std::string &url, int statu = 302); // 默认为302,临时重定向,301为永久重定向
bool Close();
};
类实现
// HttpResponse响应模块功能设计
class HttpResponse
{
private:
int _statu;
bool _redirect_flag; // 重定向标志
std::string _body;
std::string _redirect_url; // 重定向地址
std::unordered_map<std::string, std::string> _headers;
public:
HttpResponse() : _redirect_flag(false), _statu(200) {}
HttpResponse(int statu) : _redirect_flag(false), _statu(statu) {}
void ReSet() // 重置
{
_statu = 200;
_redirect_flag = false;
_body.clear();
_redirect_url.clear();
_headers.clear();
}
// 插入头部字段
void SetHeader(const std::string &key, const std::string &val)
{
_headers.insert(std::make_pair(key, val));
}
// 判断是否存在指定头部字段
bool HasHeader(const std::string &key)
{
auto it = _headers.find(key);
if (it == _headers.end())
return false;
return true;
}
// 获取指定头部字段的值
std::string GetHeader(const std::string &key)
{
auto it = _headers.find(key);
if (it == _headers.end())
return "";
return it->second;
}
// 正文设置
void SetContent(std::string &body, const std::string &type = "text/html")
{
_body = body;
SetHeader("Cnotent-Type", type);
}
// 默认为302,临时重定向,301为永久重定向
void SetRedirect(std::string &url, int statu = 302)
{
_statu = statu;
_redirect_flag = true;
_redirect_url = url;
}
// 判断是否是短链接
bool Close()
{
// 没有Connection字段,或者有Connection字段但是值是close,则是短链接,否则就是长链接
// keep-alive是长链接的意思
if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
return true;
return false;
}
};
编译测试
编译通过,并没有发现语法上的错误