Last active
August 29, 2015 14:23
-
-
Save BryanDonovan/a7c02321b1af1eb216b2 to your computer and use it in GitHub Desktop.
Trying to use restify client with a proxy server
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
// | |
// setup: | |
// npm i restify@3.0.3 request@2.58.0 http-proxy@1.11.1 | |
// | |
var assert = require('assert'); | |
var http = require("http"); | |
var restify = require('restify'); | |
var request = require('request'); | |
var httpProxy = require('http-proxy'); | |
var restifyDone = false; | |
var requestJsDone = false; | |
var proxyCallCount = 0; | |
function exitIfDone() { | |
if (restifyDone && requestJsDone) { | |
console.log("\nAll clients finished."); | |
console.log("Proxy server called " + proxyCallCount + " time(s)"); | |
assert.equal(proxyCallCount, 2, "Expected proxy server to be called twice"); | |
process.exit(); | |
} | |
} | |
/** | |
* Set up destination server that requests should get proxied to. | |
*/ | |
http.createServer(function(req, res) { | |
console.log("\nreceived request in destination server:", req.url); | |
res.writeHead(200, {"Content-Type": "application/json"}); | |
res.write('{"hello": "world"}'); | |
res.end(); | |
}).listen(8080); | |
console.log("Destination server listening on port 8080"); | |
/** | |
* Set up proxy server. | |
*/ | |
var proxy = httpProxy.createProxyServer({}); | |
var server = http.createServer(function(req, res) { | |
console.log("\nreceived request in proxy server", req.url); | |
proxyCallCount += 1; | |
proxy.web(req, res, {target: 'http://' + req.headers.host}); | |
}); | |
console.log("Proxy server listening on port 5050"); | |
server.listen(5050); | |
/** | |
* Set up Restify client. | |
*/ | |
var restifyClient = restify.createStringClient({ | |
url: 'http://127.0.0.1:8080', | |
proxy: { | |
host: '127.0.0.1', | |
protocol: 'http:', | |
port: 5050 | |
} | |
}); | |
/** | |
* Make request with Restify client | |
*/ | |
restifyClient.get({path: '/?foo=bar&requester=restify'}, function(err, req, res, result) { | |
if (err) { | |
console.log(err); | |
console.log(err.stack); | |
} | |
console.log("\nresponse: from Restify client:", result); | |
restifyDone = true; | |
exitIfDone(); | |
}); | |
/** | |
* Make request with request.js client | |
*/ | |
request.get("http://127.0.0.1:8080?foo=bar&requester=requestJs", {proxy: "http://127.0.0.1:5050"}, function(err, response, body) { | |
if (err) { | |
console.log(err); | |
console.log(err.stack); | |
} | |
console.log("\nresponse from request.js client:", body); | |
requestJsDone = true; | |
exitIfDone(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment