HttpMessage.h 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. void UploadFormFile(const char* name, const char* filepath) {
  105. content_type = MULTIPART_FORM_DATA;
  106. form[name] = FormData(NULL, filepath);
  107. }
  108. int SaveFormFile(const char* name, const char* filepath) {
  109. if (content_type != MULTIPART_FORM_DATA) {
  110. return HTTP_STATUS_BAD_REQUEST;
  111. }
  112. FormData formdata = form[name];
  113. if (formdata.content.empty()) {
  114. return HTTP_STATUS_BAD_REQUEST;
  115. }
  116. HFile file;
  117. if (file.open(filepath, "wb") != 0) {
  118. return HTTP_STATUS_INTERNAL_SERVER_ERROR;
  119. }
  120. file.write(formdata.content.data(), formdata.content.size());
  121. return 200;
  122. }
  123. #endif
  124. HttpMessage() {
  125. type = HTTP_BOTH;
  126. Init();
  127. }
  128. virtual ~HttpMessage() {}
  129. void Init() {
  130. http_major = 1;
  131. http_minor = 1;
  132. content = NULL;
  133. content_length = 0;
  134. content_type = CONTENT_TYPE_NONE;
  135. }
  136. virtual void Reset() {
  137. Init();
  138. headers.clear();
  139. body.clear();
  140. #ifndef WITHOUT_HTTP_CONTENT
  141. json.clear();
  142. form.clear();
  143. kv.clear();
  144. #endif
  145. }
  146. // structured-content -> content_type <-> headers Content-Type
  147. void FillContentType();
  148. // body.size -> content_length <-> headers Content-Length
  149. void FillContentLength();
  150. std::string GetHeader(const char* key, const std::string& defvalue = "") {
  151. auto iter = headers.find(key);
  152. if (iter != headers.end()) {
  153. return iter->second;
  154. }
  155. return defvalue;
  156. }
  157. // headers -> string
  158. void DumpHeaders(std::string& str);
  159. // structured content -> body
  160. void DumpBody();
  161. // body -> structured content
  162. // @retval 0:succeed
  163. int ParseBody();
  164. virtual std::string Dump(bool is_dump_headers, bool is_dump_body);
  165. void* Content() {
  166. if (content == NULL && body.size() != 0) {
  167. content = (void*)body.data();
  168. }
  169. return content;
  170. }
  171. int ContentLength() {
  172. if (content_length == 0) {
  173. FillContentLength();
  174. }
  175. return content_length;
  176. }
  177. http_content_type ContentType() {
  178. if (content_type == CONTENT_TYPE_NONE) {
  179. FillContentType();
  180. }
  181. return content_type;
  182. }
  183. int String(const std::string& str) {
  184. content_type = TEXT_PLAIN;
  185. body = str;
  186. return 200;
  187. }
  188. int Data(void* data, int len) {
  189. content_type = APPLICATION_OCTET_STREAM;
  190. content = data;
  191. content_length = len;
  192. return 200;
  193. }
  194. int File(const char* filepath) {
  195. HFile file;
  196. if (file.open(filepath, "rb") != 0) {
  197. return HTTP_STATUS_NOT_FOUND;
  198. }
  199. const char* suffix = hv_suffixname(filepath);
  200. if (suffix) {
  201. content_type = http_content_type_enum_by_suffix(suffix);
  202. }
  203. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  204. content_type = APPLICATION_OCTET_STREAM;
  205. }
  206. file.readall(body);
  207. return 200;
  208. }
  209. };
  210. #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"
  211. class HV_EXPORT HttpRequest : public HttpMessage {
  212. public:
  213. http_method method;
  214. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  215. std::string url;
  216. // structured url
  217. bool https;
  218. std::string host;
  219. int port;
  220. std::string path;
  221. QueryParams query_params;
  222. // client_addr
  223. HNetAddr client_addr; // for http server save client addr of request
  224. int timeout; // for http client timeout
  225. HttpRequest() : HttpMessage() {
  226. type = HTTP_REQUEST;
  227. Init();
  228. }
  229. void Init() {
  230. headers["User-Agent"] = DEFAULT_USER_AGENT;
  231. headers["Accept"] = "*/*";
  232. method = HTTP_GET;
  233. https = 0;
  234. host = "127.0.0.1";
  235. port = DEFAULT_HTTP_PORT;
  236. path = "/";
  237. timeout = 0;
  238. }
  239. virtual void Reset() {
  240. HttpMessage::Reset();
  241. Init();
  242. url.clear();
  243. query_params.clear();
  244. }
  245. virtual std::string Dump(bool is_dump_headers, bool is_dump_body);
  246. std::string GetParam(const char* key, const std::string& defvalue = "") {
  247. auto iter = query_params.find(key);
  248. if (iter != query_params.end()) {
  249. return iter->second;
  250. }
  251. return defvalue;
  252. }
  253. // structed url -> url
  254. void DumpUrl();
  255. // url -> structed url
  256. void ParseUrl();
  257. };
  258. class HV_EXPORT HttpResponse : public HttpMessage {
  259. public:
  260. http_status status_code;
  261. const char* status_message() {
  262. return http_status_str(status_code);
  263. }
  264. HttpResponse() : HttpMessage() {
  265. type = HTTP_RESPONSE;
  266. Init();
  267. }
  268. void Init() {
  269. status_code = HTTP_STATUS_OK;
  270. }
  271. virtual void Reset() {
  272. HttpMessage::Reset();
  273. Init();
  274. }
  275. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  276. };
  277. typedef std::shared_ptr<HttpRequest> HttpRequestPtr;
  278. typedef std::shared_ptr<HttpResponse> HttpResponsePtr;
  279. // state: 0 onSucceed other onError
  280. typedef void (*HttpResponseCallback)(int state, HttpRequestPtr req, HttpResponsePtr resp, void* userdata);
  281. #endif // HTTP_MESSAGE_H_