* @param {function} fn
* @api private
*/
function request(method, url, headers, data, fn) {
function request(method, url, headers, data, fn, redirects) {
var buf = '',
redirects = redirects || 3,
url = parse(url),
path = url.pathname || '/',
search = url.search || '',
hash = url.hash || '',
port = url.port || 80,
headers = utils.mixin(headers, { host: url.hostname }),
client = http.createClient(port, url.hostname)
client.addListener('error', function(e){
fn(new Error("client failed to " + method + " `" + url.href + "'"))
})
if (headers.redirect)
redirects = headers.redirect,
delete headers.redirect
if (data) {
data = queryString.stringify(data)
headers['content-length'] = data.length
headers['content-type'] = 'application/x-www-form-urlencoded'
}
require('sys').p('req')
var req = client.request(method, path + search + hash, headers)
if (data) req.write(data)
req.addListener('response', function(res){
if (req.statusCode < 200 || req.statusCode >= 400)
e(new Error('request failed with status ' + res.statusCode + ' "' + http.STATUS_CODES[res.statusCode] + '"'))
fn(new Error('request failed with status ' + res.statusCode + ' "' + http.STATUS_CODES[res.statusCode] + '"'))
else if (res.statusCode >= 300 && res.statusCode < 400)
if (--redirects)
request(method, res.headers.location, headers, data, fn)
request(method, res.headers.location, headers, data, fn, redirects)
else
fn(new Error('maximum number of redirects reached'))
else {
res.setBodyEncoding('utf8')
res
.addListener('data', function(chunk){ buf += chunk })
exports.post = exports.create = client('post')
exports.put = exports.update = client('put')
exports.del = exports.destroy = client('delete')
exports.get('http://www.google.ca', {}, {}, function(e, content){
if (!e)
require('sys').p(content.length)
exports.get('http://google.com', {}, {}, function(e, content){
if (e) throw e
require('sys').p(content.length)
})