Skip to content

Instantly share code, notes, and snippets.

@tralamazza
Created October 26, 2012 13:04
Show Gist options
  • Select an option

  • Save tralamazza/3958674 to your computer and use it in GitHub Desktop.

Select an option

Save tralamazza/3958674 to your computer and use it in GitHub Desktop.
var url = require('url');
var PROTOCOLS = {
'http:': { agent: require('http'), port: 80 },
'https:': { agent: require('https'), port: 443 }
};
/*
* @param {String} method HTTP method ('GET', 'POST' ...)
* @param {String} uri URI (defaults protocol to HTTP)
* @param {Function} callback function(err, res){}
*/
function request(method, uri, callback) {
var parsed = url.parse(uri);
var client = PROTOCOLS[parsed.protocol || 'http:'];
if (!client)
throw new Error('invalid protocol ' + parsed.protocol);
var options = {
method: method,
host: parsed.host,
port: parsed.port || client.port,
path: parsed.path
};
var req = client.agent.request(options, function(res) {
callback(null, res);
});
req.on('error', function(err) {
callback(err);
});
return req;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment