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