Skip to content

Instantly share code, notes, and snippets.

@olegp
Created May 30, 2011 17:22
Show Gist options
  • Save olegp/999178 to your computer and use it in GitHub Desktop.
Save olegp/999178 to your computer and use it in GitHub Desktop.
CommonJS HttpClient implementation for Node using node-fibers
require('fibers');
var http = require('http');
exports.HttpClient = HttpClient;
// {method, url, headers, body}
// return value is {status:status, headers:{..}, body:[..]}
function HttpClient (settings) {
if (!(this instanceof HttpClient)) return new HttpClient(settings);
this.guts = {};
if (settings) this.setOptions(settings);
};
HttpClient.prototype = {
create : function () {
this.setOptions({
"method" : "GET",
"headers" : {},
"body" : []
});
return this;
},
setOptions : function (settings) {
for (var key in settings) if (settings.hasOwnProperty(key)) {
this.setOption(key, settings[key]);
}
return this;
},
setOption : function (key, val) {
switch (key) {
case "headers":
if (typeof val !== 'object') throw new Error(
"HttpClient: headers must be a simple object."
);
return this.setHeaders(val);
case "body":
if (typeof val.forEach !== 'function') throw new Error(
"HttpClient: body must be iterable."
);
// fallthrough
default:
this.guts[key] = val;
}
return this;
},
setHeaders : function (headers) {
for (var h in headers) if (headers.hasOwnProperty(h)) {
this.setHeader(h, headers[h]);
}
return this;
},
setHeader : function (key, val) {
if (!this.guts.hasOwnProperty("headers")) this.guts.headers = {};
this.guts.headers[key] = val;
return this;
},
write : function (data) {
var len = this.guts.headers["Content-Length"] || 0;
len += data.length;
this.guts.headers["Content-Length"] = len;
this.guts.body.push(data);
return this;
},
connect : function (decode) {
//if (decode) HttpClient.decode(resp);
return this;
},
read : function() {
var fiber = Fiber.current;
var options = {
method: this.guts.method,
host: 'www.google.com',
port: 80, //TODO extract this
path: '/'
};
var req = http.request(options, function(response) {
fiber.run(response);
});
req.end();
var response = yield();
var data = [];
response.on('data', function(chunk) {
data.push(chunk);
});
response.on('end', function() {
fiber.run();
});
yield();
return {
status: response.statusCode,
headers: response.headers,
body: data.join('')
};
},
finish : function() {
return this.connect().read();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment