当前位置:   article > 正文

HttpResponse响应模块设计与实现(http模块三)

HttpResponse响应模块设计与实现(http模块三)

 目录

类功能

类定义

类实现

编译测试


类功能

类定义

  1. // HttpResponse响应模块功能设计
  2. class HttpResponse
  3. {
  4. private:
  5. int _statu;
  6. bool _redirect_flag; // 重定向标志
  7. std::string _body;
  8. std::string _redirect_url; // 重定向地址
  9. std::unordered_map<std::string, std::string> _headers;
  10. public:
  11. void ReSet(); // 重置
  12. void SetHeader(std::string &key, std::string &val);
  13. bool HasHeader(std::string &key);
  14. std::string GetHeader(std::string &key);
  15. void SetContent(std::string &body, std::string &type);
  16. void SetRedirect(std::string &url, int statu = 302); // 默认为302,临时重定向,301为永久重定向
  17. bool Close();
  18. };

类实现

  1. // HttpResponse响应模块功能设计
  2. class HttpResponse
  3. {
  4. private:
  5. int _statu;
  6. bool _redirect_flag; // 重定向标志
  7. std::string _body;
  8. std::string _redirect_url; // 重定向地址
  9. std::unordered_map<std::string, std::string> _headers;
  10. public:
  11. HttpResponse() : _redirect_flag(false), _statu(200) {}
  12. HttpResponse(int statu) : _redirect_flag(false), _statu(statu) {}
  13. void ReSet() // 重置
  14. {
  15. _statu = 200;
  16. _redirect_flag = false;
  17. _body.clear();
  18. _redirect_url.clear();
  19. _headers.clear();
  20. }
  21. // 插入头部字段
  22. void SetHeader(const std::string &key, const std::string &val)
  23. {
  24. _headers.insert(std::make_pair(key, val));
  25. }
  26. // 判断是否存在指定头部字段
  27. bool HasHeader(const std::string &key)
  28. {
  29. auto it = _headers.find(key);
  30. if (it == _headers.end())
  31. return false;
  32. return true;
  33. }
  34. // 获取指定头部字段的值
  35. std::string GetHeader(const std::string &key)
  36. {
  37. auto it = _headers.find(key);
  38. if (it == _headers.end())
  39. return "";
  40. return it->second;
  41. }
  42. // 正文设置
  43. void SetContent(std::string &body, const std::string &type = "text/html")
  44. {
  45. _body = body;
  46. SetHeader("Cnotent-Type", type);
  47. }
  48. // 默认为302,临时重定向,301为永久重定向
  49. void SetRedirect(std::string &url, int statu = 302)
  50. {
  51. _statu = statu;
  52. _redirect_flag = true;
  53. _redirect_url = url;
  54. }
  55. // 判断是否是短链接
  56. bool Close()
  57. {
  58. // 没有Connection字段,或者有Connection字段但是值是close,则是短链接,否则就是长链接
  59. // keep-alive是长链接的意思
  60. if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
  61. return true;
  62. return false;
  63. }
  64. };

编译测试

编译通过,并没有发现语法上的错误

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/222442
推荐阅读
相关标签
  

闽ICP备14008679号