node/test/simple/test-http-proxy.js

66 lines
1.7 KiB
JavaScript
Raw Normal View History

require("../common");
2010-03-20 10:22:04 +08:00
http = require("http");
url = require("url");
2010-02-27 04:06:32 +08:00
var PROXY_PORT = PORT;
var BACKEND_PORT = PORT+1;
2009-09-28 18:36:36 +08:00
var backend = http.createServer(function (req, res) {
2010-03-19 06:49:42 +08:00
debug("backend request");
2010-02-26 04:54:48 +08:00
res.writeHead(200, {"content-type": "text/plain"});
res.write("hello world\n");
res.close();
});
2010-03-19 06:49:42 +08:00
debug("listen backend")
backend.listen(BACKEND_PORT);
2009-09-28 18:36:36 +08:00
var proxy_client = http.createClient(BACKEND_PORT);
var proxy = http.createServer(function (req, res) {
debug("proxy req headers: " + JSON.stringify(req.headers));
var proxy_req = proxy_client.request(url.parse(req.url).pathname);
proxy_req.addListener('response', function(proxy_res) {
2010-02-26 04:54:48 +08:00
res.writeHead(proxy_res.statusCode, proxy_res.headers);
proxy_res.addListener("data", function(chunk) {
res.write(chunk);
2009-06-28 02:40:43 +08:00
});
proxy_res.addListener("end", function() {
res.close();
2010-03-19 06:49:42 +08:00
debug("proxy res");
2009-06-28 02:40:43 +08:00
});
});
proxy_req.close();
});
2010-03-19 06:49:42 +08:00
debug("listen proxy")
proxy.listen(PROXY_PORT);
var body = "";
2010-03-19 06:49:42 +08:00
nlistening = 0;
function startReq () {
nlistening++;
if (nlistening < 2) return;
var client = http.createClient(PROXY_PORT);
var req = client.request("/test");
debug("client req")
req.addListener('response', function (res) {
debug("got res");
assert.equal(200, res.statusCode);
res.setBodyEncoding("utf8");
res.addListener('data', function (chunk) { body += chunk; });
res.addListener('end', function () {
proxy.close();
backend.close();
debug("closed both");
});
});
2010-03-19 06:49:42 +08:00
req.close();
}
proxy.addListener('listening', startReq);
backend.addListener('listening', startReq);
process.addListener("exit", function () {
assert.equal(body, "hello world\n");
});