HttpMessage.h 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. void DumpBody(std::string& str);
  163. // body -> structured content
  164. // @retval 0:succeed
  165. int ParseBody();
  166. virtual std::string Dump(bool is_dump_headers, bool is_dump_body);
  167. void* Content() {
  168. if (content == NULL && body.size() != 0) {
  169. content = (void*)body.data();
  170. }
  171. return content;
  172. }
  173. int ContentLength() {
  174. if (content_length == 0) {
  175. FillContentLength();
  176. }
  177. return content_length;
  178. }
  179. http_content_type ContentType() {
  180. if (content_type == CONTENT_TYPE_NONE) {
  181. FillContentType();
  182. }
  183. return content_type;
  184. }
  185. int String(const std::string& str) {
  186. content_type = TEXT_PLAIN;
  187. body = str;
  188. return 200;
  189. }
  190. int Data(void* data, int len) {
  191. content_type = APPLICATION_OCTET_STREAM;
  192. content = data;
  193. content_length = len;
  194. return 200;
  195. }
  196. int File(const char* filepath) {
  197. HFile file;
  198. if (file.open(filepath, "rb") != 0) {
  199. return HTTP_STATUS_NOT_FOUND;
  200. }
  201. const char* suffix = hv_suffixname(filepath);
  202. if (suffix) {
  203. content_type = http_content_type_enum_by_suffix(suffix);
  204. }
  205. if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) {
  206. content_type = APPLICATION_OCTET_STREAM;
  207. }
  208. file.readall(body);
  209. return 200;
  210. }
  211. };
  212. #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"
  213. class HV_EXPORT HttpRequest : public HttpMessage {
  214. public:
  215. http_method method;
  216. // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
  217. std::string url;
  218. // structured url
  219. std::string scheme;
  220. std::string host;
  221. int port;
  222. std::string path;
  223. QueryParams query_params;
  224. // client_addr
  225. HNetAddr client_addr; // for http server save client addr of request
  226. int timeout; // for http client timeout
  227. HttpRequest() : HttpMessage() {
  228. type = HTTP_REQUEST;
  229. Init();
  230. }
  231. void Init() {
  232. headers["User-Agent"] = DEFAULT_USER_AGENT;
  233. headers["Accept"] = "*/*";
  234. method = HTTP_GET;
  235. scheme = "http";
  236. host = "127.0.0.1";
  237. port = DEFAULT_HTTP_PORT;
  238. path = "/";
  239. timeout = 0;
  240. }
  241. virtual void Reset() {
  242. HttpMessage::Reset();
  243. Init();
  244. url.clear();
  245. query_params.clear();
  246. }
  247. virtual std::string Dump(bool is_dump_headers, bool is_dump_body);
  248. std::string GetParam(const char* key, const std::string& defvalue = "") {
  249. auto iter = query_params.find(key);
  250. if (iter != query_params.end()) {
  251. return iter->second;
  252. }
  253. return defvalue;
  254. }
  255. // structed url -> url
  256. void DumpUrl();
  257. // url -> structed url
  258. void ParseUrl();
  259. // Range: bytes=0-4095
  260. void SetRange(long from = 0, long to = -1) {
  261. headers["Range"] = asprintf("bytes=%ld-%ld", from, to);
  262. }
  263. bool GetRange(long& from, long& to) {
  264. auto iter = headers.find("Range");
  265. if (iter != headers.end()) {
  266. sscanf(iter->second.c_str(), "bytes=%ld-%ld", &from, &to);
  267. return true;
  268. }
  269. from = to = 0;
  270. return false;
  271. }
  272. };
  273. class HV_EXPORT HttpResponse : public HttpMessage {
  274. public:
  275. http_status status_code;
  276. const char* status_message() {
  277. return http_status_str(status_code);
  278. }
  279. HttpResponse() : HttpMessage() {
  280. type = HTTP_RESPONSE;
  281. Init();
  282. }
  283. void Init() {
  284. status_code = HTTP_STATUS_OK;
  285. }
  286. virtual void Reset() {
  287. HttpMessage::Reset();
  288. Init();
  289. }
  290. virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false);
  291. // Content-Range: bytes 0-4095/10240000
  292. void SetRange(long from, long to, long total) {
  293. headers["Content-Range"] = asprintf("bytes %ld-%ld/%ld", from, to, total);
  294. }
  295. bool GetRange(long& from, long& to, long& total) {
  296. auto iter = headers.find("Content-Range");
  297. if (iter != headers.end()) {
  298. sscanf(iter->second.c_str(), "bytes %ld-%ld/%ld", &from, &to, &total);
  299. }
  300. from = to = total = 0;
  301. return false;
  302. }
  303. };
  304. typedef std::shared_ptr<HttpRequest> HttpRequestPtr;
  305. typedef std::shared_ptr<HttpResponse> HttpResponsePtr;
  306. typedef std::function<void(const HttpResponsePtr&)> HttpResponseCallback;
  307. #endif // HTTP_MESSAGE_H_