Ver código fonte

Add responseHeaders to HttpJs and HttpNodeJs (#10809)

closes #10794
Haath 2 anos atrás
pai
commit
321dffa2a1
2 arquivos alterados com 28 adições e 0 exclusões
  1. 17 0
      std/haxe/http/HttpJs.hx
  2. 11 0
      std/haxe/http/HttpNodeJs.hx

+ 17 - 0
std/haxe/http/HttpJs.hx

@@ -30,6 +30,7 @@ import haxe.io.Bytes;
 class HttpJs extends haxe.http.HttpBase {
 	public var async:Bool;
 	public var withCredentials:Bool;
+	public var responseHeaders:Map<String, String>;
 
 	var req:js.html.XMLHttpRequest;
 
@@ -53,6 +54,7 @@ class HttpJs extends haxe.http.HttpBase {
 	public override function request(?post:Bool) {
 		this.responseAsString = null;
 		this.responseBytes = null;
+		this.responseHeaders = null;
 		var r = req = js.Browser.createXMLHttpRequest();
 		var onreadystatechange = function(_) {
 			if (r.readyState != 4)
@@ -73,6 +75,21 @@ class HttpJs extends haxe.http.HttpBase {
 				onStatus(s);
 			if (s != null && s >= 200 && s < 400) {
 				req = null;
+
+				// split headers and remove the last \r\n\r\n
+				var headers = r.getAllResponseHeaders().split('\r\n');
+				headers = headers.filter(h -> h != '');
+
+				// store response headers
+				responseHeaders = new haxe.ds.StringMap();
+				for (hline in headers) {
+					var a = hline.split(": ");
+					var hname = a.shift();
+					var hval = if (a.length == 1) a[0] else a.join(": ");
+					hval = StringTools.ltrim(StringTools.rtrim(hval));
+					responseHeaders.set(hname, hval);
+				}
+
 				success(Bytes.ofData(r.response));
 			} else if (s == null || (s == 0 && r.response == null)) {
 				req = null;

+ 11 - 0
std/haxe/http/HttpNodeJs.hx

@@ -27,6 +27,8 @@ import js.node.Buffer;
 import haxe.io.Bytes;
 
 class HttpNodeJs extends haxe.http.HttpBase {
+	public var responseHeaders:Map<String, String>;
+
 	var req:js.node.http.ClientRequest;
 
 	public function new(url:String) {
@@ -47,6 +49,7 @@ class HttpNodeJs extends haxe.http.HttpBase {
 	public override function request(?post:Bool) {
 		responseAsString = null;
 		responseBytes = null;
+		responseHeaders = null;
 		var parsedUrl = new js.node.url.URL(url);
 		var secure = (parsedUrl.protocol == "https:");
 		var host = parsedUrl.hostname;
@@ -97,6 +100,14 @@ class HttpNodeJs extends haxe.http.HttpBase {
 				var buf = (data.length == 1 ? data[0] : Buffer.concat(data));
 				responseBytes = Bytes.ofData(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
 				req = null;
+
+				// store response headers
+				responseHeaders = new haxe.ds.StringMap();
+				for (field in Reflect.fields(res.headers))
+				{
+					responseHeaders.set(field, Reflect.field(res.headers, field));
+				}
+
 				if (s != null && s >= 200 && s < 400) {
 					success(responseBytes);
 				} else {