forked from mweibel/candy-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
55 lines (50 loc) · 1.59 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
var config = require(__dirname + '/config'),
fs = require('fs'),
http = require('http'),
staticServer = new(require('node-static').Server)(__dirname + '/public'),
indexFile;
// parse index file only once
fs.readFile(__dirname + '/public/index.html', 'ascii', function(err, data) {
indexFile = data.replace('OPTIONS', '{ core: ' + JSON.stringify(config.candy.core) + ', view: ' + JSON.stringify(config.candy.view) + '}');
var connect = '';
if(Array.isArray(config.candy.connect) && config.candy.connect.length > 0) {
var connect = "'" + config.candy.connect.join("', '") + "'";
}
indexFile = indexFile.replace('CONNECT', connect);
});
http.createServer(function (request, response) {
// http-bind proxy
if(request.url === '/http-bind/') {
var proxy_req = http.request({
host: config.http_bind.host,
port: config.http_bind.port,
path: config.http_bind.path,
method: request.method
});
proxy_req.on('response', function(proxy_response) {
proxy_response.on('data', function(chunk) {
response.write(chunk, 'binary');
});
proxy_req.on('end', function() {
response.end();
});
response.writeHead(proxy_response.statusCode, proxy_response.headers);
});
request.on('data', function(chunk) {
proxy_req.write(chunk, 'binary');
});
request.on('end', function() {
proxy_req.end();
});
// static files
} else {
request.on('end', function() {
if(request.url === '/' || request.url === '/index.html') {
response.write(indexFile, 'ascii');
response.end();
} else {
staticServer.serve(request, response);
}
});
}
}).listen(config.app.port);