forked from brentley/ecsdemo-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
66 lines (56 loc) · 1.87 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
// use the express framework
var express = require('express');
var app = express();
var fs = require('fs');
var code_hash = fs.readFileSync('code_hash.txt','utf8');
console.log (code_hash);
// internal-ip: detect the correct IP based on default gw
var internalip = require('internal-ip');
var ipaddress = internalip.v4.sync();
// use ipaddress to find interface netmask
var ifaces = require('os').networkInterfaces();
for (var dev in ifaces) {
// ... and find the one that matches the criteria
var iface = ifaces[dev].filter(function(details) {
return details.address === `${ipaddress}` && details.family === 'IPv4';
});
if(iface.length > 0) ifacenetmask = iface[0].netmask;
}
// ip: separate out the network using the subnet mask
var ipnet = require('ip');
var network = ipnet.mask(`${ipaddress}`, `${ifacenetmask}`)
// morgan: generate apache style logs to the console
var morgan = require('morgan')
app.use(morgan('combined'));
// express-healthcheck: respond on /health route for LB checks
app.use('/health', require('express-healthcheck')());
// label the AZ based on which subnet we are on
switch (network) {
case '10.0.100.0':
var az = '1a';
break;
case '10.0.101.0':
var az = '1b';
break;
case '10.0.102.0':
var az = '1c';
break;
default:
var az = 'unknown'
break;
}
// main route
app.get('/', function (req, res) {
res.set({
'Content-Type': 'text/plain'
})
res.send(`Node.js backend: Hello! from ${ipaddress} in AZ-${az} commit ${code_hash}`);
// res.send(`Hello World! from ${ipaddress} in AZ-${az} which has been up for ` + process.uptime() + 'ms');
});
// health route - variable subst is more pythonic just as an example
var server = app.listen(3000, function() {
var port = server.address().port;
console.log('Example app listening on port %s!', port);
});
// export the server to make tests work
module.exports = server;