Created
June 23, 2014 01:57
-
-
Save alanhoff/f3ab9b6f79def76a3f3e to your computer and use it in GitHub Desktop.
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
var httpProxy = require('http-proxy'); | |
var http = require('http'); | |
var domain = require('domain'); | |
var proxy = httpProxy.createProxyServer(); | |
// Criamos um server normal para escutar na porta 80 | |
var server = http.createServer(); | |
// Um objeto com o nome dos domínios que podemos | |
// redirecionar. | |
var sites = { | |
'sitea.com.br' : 'http://127.0.0.1:8080', | |
'siteb.com.br' : 'http://127.0.0.1:8080', | |
'sitec.com.br' : 'http://127.0.0.1:8080' | |
}; | |
// Essa função será parassada com o parâmetro do evento | |
// 'request' no servidor http e https | |
var handler = function(req, res){ | |
var d = domain.create(); | |
// Adicionamos a requisição e a resposta ao domínio | |
d.add(req); | |
d.add(res); | |
d.on('error', function(err){ | |
// Em caso de erro mandamos a msg para o console.error | |
console.error('Erro ao tentar conexão com %s', req.headers.host); | |
console.error(err.stack); | |
// Se a resposta já foi iniciada, matamos a conexão | |
if(res.headersSent) | |
return req.socket.destroy(); | |
// Se ainda não foi, respondemos com o erro | |
res.writeHead(500, { | |
'Content-Type' : 'text/plain; charset=utf-8' | |
}); | |
res.write('Erro interno no servidor.'); | |
res.end(); | |
}); | |
var host = req.headers.host; | |
if(!sites[host]){ | |
res.writeHead(404, { | |
'Content-Type' : 'text/plain; charset=utf-8' | |
}); | |
res.write('O site acessado não está aqui...'); | |
return res.end(); | |
} | |
d.run(function(){ | |
proxy.web(req, res, {target : sites[host]}); | |
}); | |
}; | |
// Request vindo pelo servidor normal, porta 80 | |
server.on('request', handler); | |
// Iniciando o servidor http | |
server.listen(80); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment