var HTTPResult = require('./http-result') , HTTP = require('http') , HTTPS = require('https') , URL = require('url') , QS = require('querystring') , _ = require('underscore') ; module.exports = function(url, options) { var result = new HTTPResult(); var body = options.body; delete options.body; var json = options.json; delete options.json; var reqOpts = _.isString(url) ? URL.parse(url) : url; _.extend(reqOpts,options); if ( json === true ) { options.headers = options.headers || {}; _.extend(options.headers,{ 'Content-Type': 'application/json', 'Accepts': 'application/json' }); } if ( reqOpts.qs ) { reqOpts.path = (reqOpts.path||'')+'?'+QS.stringify(reqOpts.qs); delete reqOpts.qs; } var protocol = reqOpts.protocol; var httpModule; if ( protocol === 'http:' ) { httpModule = HTTP; } else if ( protocol === 'https:' ) { httpModule = HTTPS; } else { throw new Error("Unknown protocol "+protocol); } var req = httpModule.request(reqOpts); req.on('response', function(response) { var data = ""; response.setEncoding('utf8'); response.on('data', function(chunk) { data += chunk; }); response.on('end', function() { var body; try { if ( json ) { if ( data ) { body = JSON.parse(data); } } else { body = data; } result.set(response.statusCode,body); } catch (ex) { console.log('error',data); result.set(-1,ex); } }); response.on('error', function(error) { result.set(-1,error); }); }); req.on('error', function(error){ result.set(-1,error); }); if ( body ) { req.write(json ? JSON.stringify(body) : body); } req.end(); return result; };