Skip to content

Instantly share code, notes, and snippets.

@xolf
Created December 27, 2015 20:34
Show Gist options
  • Save xolf/f79a1f939d7dc64c9894 to your computer and use it in GitHub Desktop.
Save xolf/f79a1f939d7dc64c9894 to your computer and use it in GitHub Desktop.
var http = require('http'),
httpProxy = require('http-proxy'),
request = require('request'),
fs = require('fs'),
servers =
{
'localhost' : 'http://example.com',
'homeworker.li' : 'http://epicwebsite.com'
},
run = true;
var proxy = httpProxy.createProxyServer();
var time = Date.now() / 1000 | 0 + ' ';
var space = " ";
// Generates the error page
function errorPage(req, res, target, time)
{
if(!res.headersSent) {
console.log(space + " | \n" +
space + " +--> Tunnelling failed\n");
res.writeHead(401, { 'Content-Type': 'text/html' });
var content = fs.readFileSync('error.html',{'encoding' : 'utf-8'});
res.end(content);
return false;
}
}
//
// Create your server that makes an operation that waits a while
// and then proxies the request
//
http.createServer(function (req, res) {
run = true;
var target = servers[req.headers.host];
time = Date.now() / 1000 | 0 + ' ';
request({
url : target,
timeout: 2000
}, function (e, response, body) {
if(e) run = errorPage(req, res, target, time);
});
if(target)
{
proxy.on('error', function (err, req, res) {
//console.log("\n" + err);
});
if(run)
{
if(!res.headersSent) {
console.log(time + ' ' + req.headers.host + ' => ' + target);
proxy.web(req, res, {
target: target,
changeOrigin: true
});
}
}
}
if(!target)
{
run = errorPage(req, res, target, time);
}
}).listen(80);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment