这个模块和上面的请求模块就是相反的,主要存储 HTTP 的响应信息,在进行业务处理的同时,让使用者向 Response 中填充响应要素,完毕后将其组织成为 HTTP 响应格式的数据,发送给客户端,这样子能让 HTTP 响应的过程操作变得简单!
其实响应内容不需要包括响应报文中的全部要素(因为有些是可以通过工具类模块获取的,或者是 http 协议本身自带的),只需要下面几个关键的:
- 状态码
- 头部字段
- 响应正文
- 重定向信息(是否进行重定向的标志,重定向的路径)

所以需要提供以下接口:
- 头部字段的新增、查询和获取
- 长短连接的判断与设置
- 正文的设置
- 重定向的设置
class HttpResponse
{
public:
int _status; // 状态码
std::string _body; // 响应正文
std::unordered_map<std::string, std::string> _header; // 头部字段
bool _is_redirect; // 是否重定向的标志
std::string _redirect_path; // 重定向路径
public:
HttpResponse();
// 成员变量清理接口
void reset();
// 插入头部字段
void set_header(const std::string& key, const std::string& val);
// 判断是否存在指定头部字段
bool has_header(const std::string& key) const;
// 获取指定头部字段的值
std::string get_header_val(const std::string& key) const;
// 设置响应正文
void set_content(const std::string& body, const std::string& type = "text/html");
// 设置重定向信息
void set_redirect(const std::string& url, int status = 302);
// 判断是否为短连接
bool is_short_connection() const;
};Ⅱ. 接口实现
接口有些甚至和请求模块是一样的,比较简单,这里也不细讲了,具体参考代码!
class HttpResponse
{
public:
int _status; // 状态码
std::string _body; // 响应正文
std::unordered_map<std::string, std::string> _header; // 头部字段
bool _is_redirect; // 是否重定向的标志
std::string _redirect_path; // 重定向路径
public:
HttpResponse(int status = 200)
: _is_redirect(false)
, _status(status)
{}
// 成员变量清理接口
void reset()
{
_status = 200;
_is_redirect = false;
_body.clear();
_header.clear();
_redirect_path.clear();
}
// 插入头部字段
void set_header(const std::string& key, const std::string& val) { _header[key] = val; }
// 判断是否存在指定头部字段
bool has_header(const std::string& key) const
{
auto it = _header.find(key);
if(it == _header.end())
return false;
return true;
}
// 获取指定头部字段的值
std::string get_header_val(const std::string& key) const
{
auto it = _header.find(key);
if(it == _header.end())
return "";
return it->second;
}
// 设置响应正文
void set_content(const std::string& body, const std::string& type = "text/html")
{
_body = body;
set_header("Content-Type", type);
}
// 设置重定向信息
void set_redirect(const std::string& url, int status = 302)
{
_status = status;
_is_redirect = true;
_redirect_path = url;
}
// 判断是否为短连接
bool is_short_connection() const
{
// 通过头部字段中的Connection来判断,如果是close表示短连接,keep-alive表示长连接
bool ret = has_header("Connection");
if(ret == false)
return 0;
return get_header_val("Connection") == "close";
}
};