http-master-proxy
proxy mutable HTTP traffic to an elected master
useful if you have a HTTP api where writes must be sent to an elected master but reads can be served from any node in the cluster
install
$ npm install http-master-proxy
usage
Create a locked node so we have a consensus on the leader
Then make a function which will proxy POST,PUT and DELETE requests onto the elected master
var http = var locked = var masterProxy = var serverid = processenvNODEIDvar serveraddress = '127.0.0.1:' + processenvNODEPORT // create a locker passing etcd connection detailsvar locker = // create a lock with a value that is the address for our HTTP servervar node = var proxy = var server = http nodestartserver
If we ran 3 copies of the server above:
$ NODEID=node1 NODEPORT=8080 node example.js$ NODEID=node2 NODEPORT=8081 node example.js$ NODEID=node3 NODEPORT=8082 node example.js
We can see that the server we hit will handle the request:
$ curl -L http://127.0.0.1:8080/api/v1/blogget node1$ curl -L http://127.0.0.1:8081/api/v1/blogget node2$ curl -L http://127.0.0.1:8082/api/v1/blogget node3
Lets see which server is currently elected as master:
$ curl -L http://127.0.0.1:8082/api/v1/leadernode2
Then we should expect node2 to handle all POST requests across the whole cluster:
$ curl -L http://127.0.0.1:8080/api/v1/blog -XPOST -d value=barpost node2$ curl -L http://127.0.0.1:8081/api/v1/blog -XPOST -d value=barpost node2$ curl -L http://127.0.0.1:8082/api/v1/blog -XPOST -d value=barpost node2
api
var proxy = electedhttp(leaderfn, addressfn)
Create a proxy function that will proxy POST, PUT and DELETE requests
leaderfn
is a function that returns a boolean as to whether this node is the current master
addressfn
is a function that returns the address of the current master
var handler = proxy(function handle(req, res){})
Return a handler function that will be proxied to the master for POST,PUT and DELETE requests
var server = http
license
MIT