HttpNodeJs.hx 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. /*
  2. * Copyright (C)2005-2019 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package haxe.http;
  23. #if nodejs
  24. import js.node.Buffer;
  25. import haxe.io.Bytes;
  26. class HttpNodeJs extends haxe.http.HttpBase {
  27. public var responseHeaders:Map<String, String>;
  28. var req:js.node.http.ClientRequest;
  29. public function new(url:String) {
  30. super(url);
  31. }
  32. /**
  33. Cancels `this` Http request if `request` has been called and a response
  34. has not yet been received.
  35. **/
  36. public function cancel() {
  37. if (req == null)
  38. return;
  39. req.abort();
  40. req = null;
  41. }
  42. public override function request(?post:Bool) {
  43. responseAsString = null;
  44. responseBytes = null;
  45. responseHeaders = null;
  46. var parsedUrl = new js.node.url.URL(url);
  47. var secure = (parsedUrl.protocol == "https:");
  48. var host = parsedUrl.hostname;
  49. var path = parsedUrl.pathname;
  50. var port = if (parsedUrl.port != null) Std.parseInt(parsedUrl.port) else (secure ? 443 : 80);
  51. var h:Dynamic = {};
  52. for (i in headers) {
  53. var arr = Reflect.field(h, i.name);
  54. if (arr == null) {
  55. arr = new Array<String>();
  56. Reflect.setField(h, i.name, arr);
  57. }
  58. arr.push(i.value);
  59. }
  60. if (postData != null || postBytes != null)
  61. post = true;
  62. var uri = null;
  63. for (p in params) {
  64. if (uri == null)
  65. uri = "";
  66. else
  67. uri += "&";
  68. uri += StringTools.urlEncode(p.name) + "=" + StringTools.urlEncode(p.value);
  69. }
  70. var question = path.split("?").length <= 1;
  71. if (uri != null)
  72. path += (if (question) "?" else "&") + uri;
  73. var opts = {
  74. protocol: parsedUrl.protocol,
  75. hostname: host,
  76. port: port,
  77. method: post ? 'POST' : 'GET',
  78. path: path,
  79. headers: h
  80. };
  81. function httpResponse(res) {
  82. res.setEncoding('binary');
  83. var s = res.statusCode;
  84. if (s != null)
  85. onStatus(s);
  86. var data = [];
  87. res.on('data', function(chunk:String) {
  88. data.push(Buffer.from(chunk, 'binary'));
  89. });
  90. res.on('end', function(_) {
  91. var buf = (data.length == 1 ? data[0] : Buffer.concat(data));
  92. responseBytes = Bytes.ofData(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
  93. req = null;
  94. // store response headers
  95. responseHeaders = new haxe.ds.StringMap();
  96. for (field in Reflect.fields(res.headers))
  97. {
  98. responseHeaders.set(field, Reflect.field(res.headers, field));
  99. }
  100. if (s != null && s >= 200 && s < 400) {
  101. success(responseBytes);
  102. } else {
  103. onError("Http Error #" + s);
  104. }
  105. });
  106. }
  107. req = secure ? js.node.Https.request(untyped opts, httpResponse) : js.node.Http.request(untyped opts, httpResponse);
  108. if (post)
  109. if (postData != null) {
  110. req.write(postData);
  111. } else if(postBytes != null) {
  112. req.setHeader("Content-Length", '${postBytes.length}');
  113. req.write(Buffer.from(postBytes.getData()));
  114. }
  115. req.end();
  116. }
  117. }
  118. #end