[525] | 1 | var HTTPResult = require('./http-result') |
---|
[527] | 2 | , HTTP = require('http') |
---|
| 3 | , HTTPS = require('https') |
---|
| 4 | , URL = require('url') |
---|
[529] | 5 | , QS = require('querystring') |
---|
[525] | 6 | , _ = require('underscore') |
---|
| 7 | ; |
---|
| 8 | |
---|
| 9 | module.exports = function(url, options) { |
---|
| 10 | |
---|
| 11 | var result = new HTTPResult(); |
---|
| 12 | |
---|
[527] | 13 | var body = options.body; |
---|
| 14 | delete options.body; |
---|
| 15 | |
---|
| 16 | var json = options.json; |
---|
| 17 | delete options.json; |
---|
| 18 | |
---|
| 19 | var reqOpts = _.isString(url) ? URL.parse(url) : url; |
---|
| 20 | _.extend(reqOpts,options); |
---|
| 21 | if ( json === true ) { |
---|
| 22 | options.headers = options.headers || {}; |
---|
| 23 | _.extend(options.headers,{ |
---|
| 24 | 'Content-Type': 'application/json', |
---|
| 25 | 'Accepts': 'application/json' |
---|
| 26 | }); |
---|
| 27 | } |
---|
[529] | 28 | if ( reqOpts.qs ) { |
---|
| 29 | reqOpts.path = (reqOpts.path||'')+'?'+QS.stringify(reqOpts.qs); |
---|
| 30 | delete reqOpts.qs; |
---|
| 31 | } |
---|
[527] | 32 | |
---|
| 33 | var protocol = reqOpts.protocol; |
---|
| 34 | var httpModule; |
---|
| 35 | if ( protocol === 'http:' ) { |
---|
| 36 | httpModule = HTTP; |
---|
| 37 | } else if ( protocol === 'https:' ) { |
---|
| 38 | httpModule = HTTPS; |
---|
| 39 | } else { |
---|
| 40 | throw new Error("Unknown protocol "+protocol); |
---|
| 41 | } |
---|
| 42 | |
---|
| 43 | var req = httpModule.request(reqOpts); |
---|
| 44 | req.on('response', function(response) { |
---|
| 45 | var data = ""; |
---|
| 46 | response.setEncoding('utf8'); |
---|
| 47 | response.on('data', function(chunk) { |
---|
| 48 | data += chunk; |
---|
| 49 | }); |
---|
| 50 | response.on('end', function() { |
---|
| 51 | var body; |
---|
| 52 | try { |
---|
| 53 | if ( json ) { |
---|
| 54 | if ( data ) { body = JSON.parse(data); } |
---|
| 55 | } else { |
---|
| 56 | body = data; |
---|
| 57 | } |
---|
| 58 | result.set(response.statusCode,body); |
---|
| 59 | } catch (ex) { |
---|
| 60 | console.log('error',data); |
---|
| 61 | result.set(-1,ex); |
---|
| 62 | } |
---|
| 63 | }); |
---|
| 64 | response.on('error', function(error) { |
---|
| 65 | result.set(-1,error); |
---|
| 66 | }); |
---|
[525] | 67 | }); |
---|
[527] | 68 | req.on('error', function(error){ |
---|
| 69 | result.set(-1,error); |
---|
| 70 | }); |
---|
[525] | 71 | |
---|
[527] | 72 | if ( body ) { |
---|
| 73 | req.write(json ? JSON.stringify(body) : body); |
---|
| 74 | } |
---|
| 75 | req.end(); |
---|
| 76 | |
---|
[525] | 77 | return result; |
---|
| 78 | |
---|
| 79 | }; |
---|