Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

add easily accessible get/post functionality

  • Loading branch information...
commit 717d514a266baf3ec8f0a5be469ff652a6d9531a 1 parent 37ee6ce
@cloudshift authored
Showing with 74 additions and 0 deletions.
  1. +74 −0 cloudshift/Http.hx
View
74 cloudshift/Http.hx
@@ -46,4 +46,78 @@ class Http {
return new cloudshift.http.HttpImpl();
}
+ public static function
+ get(url:String,?params:Dynamic,?headers:Dynamic):Outcome<String,String> {
+ var
+ oc = Core.outcome(),
+ pu = Node.url.parse(url),
+ client = Node.http.createClient(Std.parseInt((pu.port == null) ? "80" : pu.port),pu.hostname),
+ myheaders = {"host":pu.hostname},
+ request;
+
+ if (headers != null)
+ for( h in Reflect.fields(headers)) {
+ Reflect.setField(myheaders,h,Reflect.field(headers,h));
+ }
+
+ request = client.request("GET",url,myheaders);
+
+ request.addListener('response',function(response:NodeHttpClientResp) {
+ var resp = new StringBuf();
+ response.on("data", function (chunk) {
+ resp.add(chunk);
+ });
+ response.on("end",function() {
+ oc.resolve(Right(resp.toString()));
+ });
+ });
+
+ if (params != null) {
+ request.end(Node.queryString.stringify(params));
+ } else
+ request.end();
+
+ return oc;
+ }
+
+ public static function
+ post(url:String,payload:Dynamic,urlEncoded=true,?headers:Dynamic):Outcome<String,String> {
+ var
+ oc = Core.outcome(),
+ pu = Node.url.parse(url),
+ client = Node.http.createClient(Std.parseInt((pu.port == null) ? "80" : pu.port),pu.hostname),
+ myheaders = {"host":pu.hostname},
+ request;
+
+ if (headers != null)
+ for( h in Reflect.fields(headers)) {
+ Reflect.setField(myheaders,h,Reflect.field(headers,h));
+ }
+
+ if (urlEncoded)
+ Reflect.setField(myheaders,'Content-Type','application/x-www-form-urlencoded');
+ else
+ Reflect.setField(myheaders,"Content-Length",Std.string(Std.string(payload).length));
+
+ request = client.request("POST",url,myheaders);
+
+ request.addListener('response',function(response:NodeHttpClientResp) {
+ var resp = new StringBuf();
+ response.on("data", function (chunk) {
+ resp.add(chunk);
+ });
+ response.on("end",function() {
+ oc.resolve(Right(resp.toString()));
+ });
+ });
+
+ if (urlEncoded)
+ request.end(Node.queryString.stringify(payload));
+ else
+ request.end(payload);
+
+ return oc;
+ }
+
+
}
Please sign in to comment.
Something went wrong with that request. Please try again.