Last active
October 27, 2015 21:37
-
-
Save evanlucas/1a9d6f650e6fd9aaf88d to your computer and use it in GitHub Desktop.
http-lookup.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const http = require('http') | |
const net = require('net') | |
const dns = require('dns') | |
// this will hold our hosts | |
// [ { family: 4, address: <ip address> } ] | |
var hosts | |
// custom lookup function | |
// the callback must be called with the following signature: | |
// function(err, family, address) | |
// where family is either 4 for IPv4 or 6 for IPv6 | |
function lookup(hostname, opts, cb) { | |
console.log('lookup', hostname) | |
opts = opts || {} | |
// this fetches all of the records instead of a single one | |
opts.all = true | |
if (hosts && hosts.length) { | |
// make sure to defer it | |
// otherwise, there are some special cases where an error | |
// could be thrown before a listener is added | |
setImmediate(() => { | |
const host = random() | |
console.log('Already looked up...using', host) | |
cb(null, host.address, host.family) | |
}) | |
return | |
} | |
// we don't have any records cached, so go ahead and do the actual | |
// dns lookup | |
dns.lookup(hostname, opts, function(err, results) { | |
if (err) return cb(err) | |
hosts = results | |
// get random one | |
const host = random() | |
console.log('fresh lookup...using', host) | |
cb(null, host.address, host.family) | |
}) | |
} | |
function random() { | |
return hosts[Math.floor(Math.random() * hosts.length)] | |
} | |
function get() { | |
http.get({ | |
hostname: 'google.com' | |
, path: '/' | |
// specify our custom lookup function here | |
, lookup: lookup | |
}, function(res) { | |
console.log('RESPONSE', res.statusCode) | |
}).on('error', function(err) { | |
console.error('ERROR', err) | |
}) | |
} | |
get() | |
setTimeout(get, 5000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment