HttpMessage.h 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #ifndef HTTP_MESSAGE_H_
  2. #define HTTP_MESSAGE_H_
  3. #include <memory>
  4. #include <string>
  5. #include <map>
  6. #include "hexport.h"
  7. #include "hbase.h"
  8. #include "hstring.h"
  9. #include "hfile.h"
  10. #include "httpdef.h"
  11. #include "http_content.h"
  12. typedef std::map<std::string, std::string, StringCaseLess> http_headers;
  13. typedef std::string http_body;
  14. struct HNetAddr {
  15. std::string ip;
  16. int port;
  17. std::string ipport() {
  18. return asprintf("%s:%d", ip.c_str(), port);
  19. }
  20. };
  21. class HV_EXPORT HttpMessage {
  22. public:
  23. int type;
  24. unsigned short http_major;
  25. unsigned short http_minor;
  26. http_headers headers;
  27. http_body body;
  28. // structured content
  29. void* content; // DATA_NO_COPY
  30. int content_length;
  31. http_content_type content_type;
  32. #ifndef WITHOUT_HTTP_CONTENT
  33. hv::Json json; // APPLICATION_JSON
  34. MultiPart form; // MULTIPART_FORM_DATA
  35. hv::KeyValue kv; // X_WWW_FORM_URLENCODED
  36. // T=[bool, int64_t, double]
  37. template<typename T>
  38. T Get(const char* key, T defvalue = 0);
  39. std::string GetString(const char* key, const std::string& = "");
  40. bool GetBool(const char* key, bool defvalue = 0);
  41. int64_t GetInt(const char* key, int64_t defvalue = 0);
  42. double GetFloat(const char* key, double defvalue = 0);
  43. template<typename T>
  44. void Set(const char* key, const T& value) {
  45. switch (content_type) {
  46. case APPLICATION_JSON:
  47. json[key] = value;
  48. break;
  49. case MULTIPART_FORM_DATA:
  50. form[key] = FormData(value);
  51. break;
  52. case X_WWW_FORM_URLENCODED:
  53. kv[key] = hv::to_string(value);
  54. break;
  55. default:
  56. break;
  57. }
  58. }
  59. /*
  60. * null: Json(nullptr);
  61. * boolean: Json(true);
  62. * number: Json(123);
  63. * string: Json("hello");
  64. * object: Json(std::map<string, ValueType>);
  65. * Json(hv::Json::object({
  66. {"k1", "v1"},
  67. {"k2", "v2"}
  68. }));
  69. * array: Json(std::vector<ValueType>);
  70. Json(hv::Json::object(
  71. {1, 2, 3}
  72. ));
  73. */
  74. template<typename T>
  75. int Json(const T& t) {
  76. content_type = APPLICATION_JSON;
  77. json = t;
  78. return 200;
  79. }
  80. #endif
  81. HttpMessage() {
  82. type = HTTP_BOTH;
  83. Init();
  84. }
  85. virtual ~HttpMessage() {}
  86. void Init() {
  87. http_major = 1;
  88. http_minor = 1;
  89. content = NULL;
  90. content_length = 0;
  91. content_type = CONTENT_TYPE_NONE;
  92. }
  93. virtual void Reset() {
  94. Init();
  95. headers.clear();
  96. body.clear();
  97. #ifndef WITHOUT_HTTP_CONTENT
  98. json.clear();
  99. form.clear();
  100. kv.clear();
  101. #endif
  102. }
  103. // structured-content -> content_type <-> headers Content-Type
  104. void FillContentType();
  105. // body.size -> content_length <-> headers Content-Length
  106. void FillContentLength();
  107. std::string GetHeader(const char* key) {
  108. auto iter = headers.find(key);
  109. if (iter != headers.end()) {
  110. return iter->second;
  111. }
  112. return "";
  113. }
  114. // headers -> string
  115. void DumpHeaders(std::string& str);
  116. // structured content -> body
  117. void DumpBody();
  118. // body -> structured content
  119. // @retval 0:succeed
  120. int ParseBody();
  121. virtual std::string Dump(bool is_dump_headers, bool is_dump_body);
  122. void* Content() {
  123. if (content == NULL && body.size() != 0) {
  124. content = (void*)body.data();
  125. }
  126. return content;
  127. }
  128. int ContentLength() {
  129. if (content_length == 0) {
  130. FillContentLength();
  131. }
  132. return content_length;
  133. }
  134. http_content_type ContentType() {
  135. if (content_type == CONTENT_TYPE_NONE) {
  136. FillContentType();
  137. }
  138. return content_type;
  139. }
  140. int String(const char* str) {
  141. content_type = TEXT_PLAIN;
  142. body = str;
  143. return 200;
  144. }
  145. int String(std::string& str) {
  146. content_type = TEXT_PLAIN;
  147. body = str;
  148. return 200;
  149. }
  150. int Data(void* data, int len) {
  151. content_type = APPLICATION_OCTET_STREAM;
  152. content = data;
  153. content_length = len;
  154. return 200;
  155. }
  156. int File(const char* filepath) {
  157. HFile file;
  158. if (file.open(filepath, "r") != 0) {
  159. return HTTP_STATUS_NOT_FOUND;
  160. }
  161. const char* suffix = hv_suffixname(filepath);
  162. if (suffix) {
  163. content_type = http_content_type_enum_by_suffix(suffix);
  164. }
  165. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  166. content_type = APPLICATION_OCTET_STREAM;
  167. }
  168. file.readall(body);
  169. return 200;
  170. }
  171. };
  172. #define DEFAULT_USER_AGENT "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
  173. class HV_EXPORT HttpRequest : public HttpMessage {
  174. public:
  175. http_method method;
  176. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  177. std::string url;
  178. // structured url
  179. bool https;
  180. std::string host;
  181. int port;
  182. std::string path;
  183. QueryParams query_params;
  184. // client_addr
  185. HNetAddr client_addr; // for http server save client addr of request
  186. int timeout; // for http client timeout
  187. HttpRequest() : HttpMessage() {
  188. type = HTTP_REQUEST;
  189. Init();
  190. }
  191. void Init() {
  192. headers["User-Agent"] = DEFAULT_USER_AGENT;
  193. headers["Accept"] = "*/*";
  194. method = HTTP_GET;
  195. https = 0;
  196. host = "127.0.0.1";
  197. port = DEFAULT_HTTP_PORT;
  198. path = "/";
  199. timeout = 0;
  200. }
  201. virtual void Reset() {
  202. HttpMessage::Reset();
  203. Init();
  204. url.clear();
  205. query_params.clear();
  206. }
  207. virtual std::string Dump(bool is_dump_headers, bool is_dump_body);
  208. std::string GetParam(const char* key) {
  209. auto iter = query_params.find(key);
  210. if (iter != query_params.end()) {
  211. return iter->second;
  212. }
  213. return "";
  214. }
  215. // structed url -> url
  216. void DumpUrl();
  217. // url -> structed url
  218. void ParseUrl();
  219. };
  220. class HV_EXPORT HttpResponse : public HttpMessage {
  221. public:
  222. http_status status_code;
  223. const char* status_message() {
  224. return http_status_str(status_code);
  225. }
  226. HttpResponse() : HttpMessage() {
  227. type = HTTP_RESPONSE;
  228. Init();
  229. }
  230. void Init() {
  231. status_code = HTTP_STATUS_OK;
  232. }
  233. virtual void Reset() {
  234. HttpMessage::Reset();
  235. Init();
  236. }
  237. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  238. };
  239. typedef std::shared_ptr<HttpRequest> HttpRequestPtr;
  240. typedef std::shared_ptr<HttpResponse> HttpResponsePtr;
  241. // state: 0 onSucceed other onError
  242. typedef void (*HttpResponseCallback)(int state, HttpRequestPtr req, HttpResponsePtr resp, void* userdata);
  243. #endif // HTTP_MESSAGE_H_