HttpMessage.h 9.1 KB

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