-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
89 lines (76 loc) · 2.5 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"use strict";
/*
Extremely simple http proxy that uses Redis as routing table
> redis-cli
SELECT 5
HSET proxy~router "domain" "localhost:port"
Unicode domains must be stored in the unicode form, not in punycode form
*/
var config = require("./config/" + (process.env.NODE_ENV || "development") + ".js"),
http = require("http"),
httpProxy = require('http-proxy'),
redis = require("redis"),
redisClient = redis.createClient(config.redis.port, config.redis.host),
proxy = httpProxy.createServer(),
punycode = require("punycode");
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
"Content-Type": "text/plain"
});
res.end("Something went wrong");
console.log("Proxy error");
console.log(err);
});
http.createServer(function (req, res) {
var host = (req.headers.host || "").
// remove port 80 and 443 if specified
replace(/:(80|443)$/, "").
trim().toLowerCase().
// Convert punycode domains to unicode
replace(/^[^:]+/, punycode.toUnicode);
redisClient.multi().
select(config.redis.db).
hget("proxy~router", host).
exec(function(err, replies){
if(err){
res.writeHead(500, {
"Content-Type": "text/plain"
});
res.end("Something went wrong");
console.log("Redis error");
console.log(err);
return;
}
if(!replies || !replies[1]){
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.end("Unknown hostname");
return;
}
var target = {
target: (!replies[1].match(/^https?:\/\//i) ? "http://" : "") + replies[1]
};
proxy.web(req, res, target);
});
}).listen(config.port, function(){
if(config.gid){
try{
process.setgid(config.gid);
console.log("Changed GID to %s", config.gid);
}catch(E){
console.log("Error: Failed changing GID to %s", config.gid);
console.log(E);
}
}
if(config.uid){
try{
process.setuid(config.uid);
console.log("Changed UID to %s", config.uid);
}catch(E){
console.log("Error: Failed changing UID to %s", config.uid);
console.log(E);
}
}
console.log("HTTP proxy listening on port %s", config.port);
});