HttpMessage.h 8.3 KB

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