-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
68 lines (54 loc) · 1.88 KB
/
server.js
File metadata and controls
68 lines (54 loc) · 1.88 KB
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
const { makeApp } = require('./app.js')
const db_fn = require('./database.js');
require('dotenv').config()
const GracefulShutdownManager = require('@moebius/http-graceful-shutdown').GracefulShutdownManager;
// Dependencies
const fs = require('fs');
const http = require('http');
const https = require('https');
const express = require('express');
//start server
const httpPort = 80;
const httpsPort = 443
const app = makeApp(db_fn)
//app.listen(port, ()=> console.log(`Server running on port ${port}`))
// Certificate
const privateKey = fs.readFileSync(process.env.CERTBOT_DIR + 'privkey.pem', 'utf8');
//const certificate = fs.readFileSync(process.env.CERTBOT_DIR + 'cert.pem', 'utf8');
const certificate = fs.readFileSync(process.env.CERTBOT_DIR + 'fullchain.pem', 'utf8');
//const ca = fs.readFileSync(process.env.CERTBOT_DIR + 'chain.pem', 'utf8');
const credentials = {
key: privateKey,
cert: certificate,
//ca: ca
};
// HTTP to HTTPS redirect
const httpApp = express();
httpApp.use((req, res, next) => {
if (req.secure) {
next();
} else {
const redirectUrl = 'https://' + req.headers.host + req.url;
res.redirect(301, redirectUrl);
}
});
// Starting both http & https servers
const httpServer = http.createServer(httpApp);
//const httpServer = http.createServer(app); // for load testing only with locust
const httpsServer = https.createServer(credentials, app);
// Graceful shutdown
const httpShutdownManager = new GracefulShutdownManager(httpServer);
const httpsShutdownManager = new GracefulShutdownManager(httpsServer);
process.on('SIGTERM', () => {
httpsShutdownManager.terminate(() => {
httpShutdownManager.terminate(() => {
console.log('Server is gracefully terminated');
});
});
});
httpServer.listen(httpPort, () => {
console.log('HTTP Server running on port ' + httpPort);
});
httpsServer.listen(httpsPort, () => {
console.log('HTTPS Server running on port ' + httpsPort);
});