curl.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. 'use strict';
  2. const F = require('../common/function');
  3. const request = require('request');
  4. const _ = require('underscore');
  5. _.str = require('underscore.string');
  6. var httplib = require('http');
  7. var httpslib = require('https');
  8. httplib.globalAgent.keepAlive = true;
  9. //httplib.globalAgent.maxSockets = 100000;
  10. httpslib.globalAgent.keepAlive = true;
  11. //httpslib.globalAgent.maxSockets = 100000;
  12. module.exports = function (app, commonManager) {
  13. /**
  14. * post操作
  15. * @param url url地址
  16. * @param data 数据
  17. * @returns {*}
  18. */
  19. this.post = function* (url, data, headers={}) {
  20. let res = yield sendRequest(url, data, 'post', headers);
  21. F.addDebugLogs(["send post:",url,data,headers,res]);
  22. return res;
  23. };
  24. /**
  25. * get操作
  26. * @param url url地址
  27. * @returns {*}
  28. */
  29. this.get = function* (url, headers={}) {
  30. let res = yield sendRequest(url, {}, 'get', headers);
  31. F.addDebugLogs(["send get:",url,headers,res]);
  32. return res;
  33. };
  34. /**
  35. * 同时支持http https 和设置返回编码的网络库
  36. * @param host 127.0.0.1
  37. * @param port 8081
  38. * @param route /share/v1/getconfig
  39. * @param params {userid:xxx,username:xxx}
  40. * @param headers {}
  41. * @param encoding binary/utf8
  42. * @param protoc http/https
  43. * @param timeout_time
  44. * @returns {*}
  45. */
  46. this.httpGet = function* (host, port, route, params = '', headers = {}, encoding = 'utf8', protoc = 'http', timeout_time = 20000) {
  47. let start_time = new Date().getTime();
  48. let curl_res = yield sendHttpRequest('GET', host, port, route, params, headers, encoding, protoc, timeout_time);
  49. let end_times = new Date().getTime();
  50. F.addOtherLogs("curl/curl", [route, params, ' curl res', {curl_res: curl_res, total_time: end_times - start_time}]);
  51. return curl_res;
  52. };
  53. this.httpPost = function* (host, port, route, params = '', headers = {}, encoding = 'utf8', protoc = 'http', timeout_time = 20000) {
  54. let start_time = new Date().getTime();
  55. let curl_res = yield sendHttpRequest('POST', host, port, route, params, headers, encoding, protoc, timeout_time);
  56. let end_times = new Date().getTime();
  57. F.addOtherLogs("curl/curl", [route, params, ' curl res', {curl_res: curl_res, total_time: end_times - start_time}]);
  58. return curl_res;
  59. };
  60. this.httpPostJson = function* (host, port, route, params = '', headers = {}, encoding = 'utf8', protoc = 'http', timeout_time = 20000) {
  61. let start_time = new Date().getTime();
  62. let curl_res = yield sendHttpRequest('POST', host, port, route, params, headers, encoding, protoc, timeout_time,true);
  63. let end_times = new Date().getTime();
  64. F.addOtherLogs("curl/curl", [route, params, ' curl res', {curl_res: curl_res, total_time: end_times - start_time}]);
  65. return curl_res;
  66. };
  67. /**
  68. * http模块get操作,不打印日志
  69. * @param url url地址
  70. * @returns {*}
  71. */
  72. this.httpGetNoLogs = function* (host, port, route, params = '', headers = {}, encoding = 'utf8', protoc = 'http', timeout_time = 20000) {
  73. let curl_res = yield sendHttpRequest('GET', host, port, route, params, headers, encoding, protoc, timeout_time);
  74. return curl_res;
  75. };
  76. };
  77. /**
  78. * curl发送请求
  79. * @param url url地址
  80. * @param params 参数
  81. * @param type 请求类型
  82. */
  83. function sendRequest(url, params, type = 'post', headers = {}) {
  84. type = type == 'post' ? 'post' : 'get';
  85. params = F.isNull(params) ? {} : params;
  86. return new Promise(function (resolve, reject) {
  87. let send_data = {method: type, url: url, timeout: 20000};
  88. if (type=='post') send_data.form = params;
  89. if (!F.isNull(headers)) send_data.headers = headers;
  90. request(send_data, function (error, response, body) {
  91. var res = {};
  92. if (error) {
  93. F.addErrLogs(["curl err:",error,response,body]);
  94. res = {result: 0, message: error, code:502};
  95. } else if (response.statusCode != 200) {
  96. res = {result: 0, message: response.body, code:response.statusCode};
  97. } else {
  98. res = {result: 1, data: body, code:200};
  99. }
  100. resolve(res);
  101. });
  102. });
  103. }
  104. /**
  105. * http/https模块发送请求
  106. * @param host
  107. * @param port
  108. * @param route
  109. * @param params 参数
  110. * @param headers
  111. * @param encoding 可选值: utf8 binary
  112. */
  113. function sendHttpRequest(type, host, port, route, params = {}, headers = {}, encoding = 'utf8', protoc = 'http', timeout_time = 20000,is_json=false) {
  114. if (F.isNull(headers)) headers = {};
  115. if (F.isNull(params)) params = {};
  116. let http = protoc == 'http'? httplib: httpslib;
  117. let params_str = '';
  118. for(let key in params) {
  119. params_str += key + '=' + encodeURIComponent(params[key]) + '&';
  120. }
  121. params_str = _.str.trim(params_str, '&');
  122. if (type == 'GET') {
  123. if (route.indexOf('?') == -1) route = route + '?' + params_str;
  124. else route = route + '&' + params_str;
  125. } else if (type == 'POST') {
  126. if (is_json){
  127. headers["Content-Type"] = "application/json;charset=utf-8";
  128. params_str = JSON.stringify(params);
  129. } else {
  130. headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
  131. }
  132. }
  133. headers["Connection"] = "keep-alive";
  134. let options = {
  135. hostname: host,
  136. port: port,
  137. path: route,
  138. method: type,
  139. headers: headers
  140. };
  141. if (protoc == "https") options.rejectUnauthorized = false;
  142. // F.addDebugLogs(['sendHttpRequest option', {options: options, start_time: new Date().getTime()},params_str]);
  143. let data = '';
  144. return new Promise(function (resolve, reject) {
  145. let timeoutEventId = 0;
  146. let req = http.request(options, function(res) {
  147. res.setEncoding(encoding);
  148. res.on('data', function(chunk) {
  149. data += chunk;
  150. });
  151. res.on('end', function() {
  152. clearTimeout(timeoutEventId);
  153. resolve({result: true, data: data});
  154. });
  155. res.on('abort',function(){
  156. clearTimeout(timeoutEventId);
  157. F.addDebugLogs(["exe timeout abort"]);
  158. })
  159. });
  160. req.on('timeout',function(e){
  161. req.abort();
  162. F.addDebugLogs(["exe timeout event"]);
  163. resolve({result: false, timeout: 1, errmsg:"timeout"});
  164. });
  165. req.on('error', (e) => {
  166. clearTimeout(timeoutEventId);
  167. resolve({result: false, errmsg: e.message});
  168. });
  169. if (type == 'POST') req.write(params_str);
  170. req.end();
  171. timeoutEventId=setTimeout(function(){
  172. F.addDebugLogs(["exe timeout",timeout_time]);
  173. req.emit('timeout',{message:'have been timeout...'});
  174. },timeout_time);
  175. });
  176. }