Skip to content

Commit

Permalink
Add responseHeaders to HttpJs and HttpNodeJs (#10809)
Browse files Browse the repository at this point in the history
closes #10794
  • Loading branch information
haath authored Nov 7, 2022
1 parent b2f931b commit 321dffa
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
17 changes: 17 additions & 0 deletions std/haxe/http/HttpJs.hx
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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)
Expand All @@ -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;
Expand Down
11 changes: 11 additions & 0 deletions std/haxe/http/HttpNodeJs.hx
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 321dffa

Please sign in to comment.