Last active
August 29, 2015 14:18
-
-
Save jedi4ever/8da590c05d66ffbdcffb to your computer and use it in GitHub Desktop.
monkey patch net.connect nodejs to support SRV records
This file contains 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
// Proof of concept of monkey patching net.connect to make it support SRV records | |
// If require a monkey patched connect function before any other requires we can make a generic fix for handling SRV records | |
// We need of course to handle a few different cases & more robust error handling | |
// We can require a lib and even specify a filter for which hosts to resolve SRV and which not | |
var net = require('net'); | |
var dns = require('dns'); | |
// Set a specific Nameserver to be used | |
dns.setServers(['172.17.42.1']); | |
var oconnect = net.connect; | |
var oconnect = function() { | |
console.log(arguments); | |
} | |
// Monkey Patch connect | |
net.connect = function nconnect() { | |
var type = typeof arguments[0]; | |
if (type === 'object') { | |
var host = arguments[0].host || 'localhost'; | |
// Find SRV record | |
dns.resolveSrv(host, function(err, addr) { | |
// read the port from SRV record | |
var newPort = addr[0].port; | |
// Set SRV port | |
var newArguments = Array.prototype.slice.call(arguments, 1); | |
newArguments[0][0].port = newPort; | |
// Call original function | |
oconnect.apply(this, newArguments); | |
}) | |
} else { | |
var host = arguments[0] | |
var newArguments = Array.prototype.slice.call(arguments, 1); | |
arguments[0].port = addr[0].port; | |
// handle more cases | |
// ... | |
} | |
} | |
net.connect({ port: 30 , host: 'db.service.consul'}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment