反向代理

闲来无聊,正好最近端午的项目要用WebAPI做统计,便兴起用Node.js写了一个反向代理的脚本(这两者好像没有什么联系233)。


放在这,可能自己以后要用的时候还能拿来用吧。

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
const http = require('http');
const fs = require('fs');
var config;
console.log("Loading cofing...");
fs.readFile("./config.json",(err,data) => {
if (err) throw err;
config = data.toString();
start();
});

const server = http.createServer((req,res) => {
var host = req.headers['host'];
req.headers['host']='localhost';
var dom = host.indexOf('.') == -1 ? 'localhost' : host.substr(0,host.indexOf('.'));
if (config[dom] == undefined) {
res.writeHead(404);
res.end("404 Not Found");
console.log("Got unknown subdomain: " + dom);
return;
}
var port = config[dom];
console.log("Got request from " + host + ", proxying it to localhost:" + port);

var options = {
hostname: 'localhost',
port: port,
path: req.url,
method: req.method,
headers: req.headers
};

var request = http.request(options, (response) => {
res.writeHead(response.statusCode);
response.on('error', (err) => {
res.writeHead(400);
res.end(err);
});
response.on('data', (chunk) => {
res.write(chunk);
});
response.on('end', () => {
res.end();
});
});
req.on('data', (chunk) => {
request.write(chunk);
});
request.on('error', (err) => {
res.writeHead(400);
res.end(err.toString());
});

req.on('end',() => {
request.end();
});
});

function start() {
config = JSON.parse(config);
server.listen(80);
console.log("Listening on port 80");
}