forked from chrismatthieu/nodefu
-
Notifications
You must be signed in to change notification settings - Fork 1
/
proxy.js
94 lines (70 loc) · 2.41 KB
/
proxy.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
/*
NodeFu - Nodejs hosting
This app runs on port 80 and forwards traffic to the appropriate node app
*/
var httpProxy = require('http-proxy'),
url = require('url'),
sys = require('sys');
var CouchClient = require('couch-client');
// var nodemon = require('nodemon');
// startup app.js API (use Forever in Production)
var exec = require('child_process').exec;
// exec('forever start app.js');
var spawn = require('child_process').spawn;
// var app = spawn('node', ['app.js']);
// var forever = require('forever');
var Nodefu = CouchClient("http://nodefu.couchone.com:80/apps");
// Launch all nodefu hosted apps
// spawn('ruby', ['launchapps.rb']);
// NODEJS ISSUE WITH TOO MANY OPEN FILES
// Nodefu.view('/apps/_design/nodeapps/_view/all', {}, function(err, doc) {
// for (var key in doc.rows) {
// var obj = doc.rows[key];
// sys.puts('launching: subdomain ' + obj["value"]["_id"] + ' on port ' + obj["value"]['port']);
// process.chdir('apps/' + obj["value"]['_rev']);
// spawn('node', [obj["value"]['start']]);
//
// // var child = new (forever.Forever)(obj["value"]['start'], {
// // silent: true,
// // options: []
// // });
// // child.start();
//
// process.chdir('../..');
//
// }
//
// });
httpProxy.createServer(function (req, res, proxy) {
var hostname = req.headers.host;
var subdomain = hostname.substring(0,hostname.indexOf("."));
// Show headers for testing
sys.puts(JSON.stringify(req.headers));
if (subdomain == 'api') {
// if (req.url != '/user' && req.method != 'POST') {
// Check for basic auth on API
// send browser request for user credentials
if(req.headers.authorization==undefined) {
res.writeHead(401, {'Content-Type': 'text/plain', 'WWW-Authenticate': 'Basic'});
res.end('password?\n');
} else {
// Redirect to Nodefu's home page if no credentials are provided
proxy.proxyRequest(4001, 'localhost');
};
// };
} else if (subdomain && subdomain != 'www' && subdomain != 'api') {
// redirect to subdomain's port by looking up subdomain and port in couchdb
Nodefu.get(subdomain, function (err, doc) {
if (doc){
proxy.proxyRequest(doc.port, 'localhost');
}
});
} else {
// redirect to Nodefu's home page
proxy.proxyRequest(4001, 'localhost');
};
}).listen(80); // Use port 80 in production
sys.puts('NodeFu started on port 80');
process.on('uncaughtException', function (err) {
console.log(err);
});