Skip to content

Instantly share code, notes, and snippets.

@droganaida
Created August 13, 2023 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save droganaida/cdea20db5d5025cf7f1bbbebdd077b19 to your computer and use it in GitHub Desktop.
Save droganaida/cdea20db5d5025cf7f1bbbebdd077b19 to your computer and use it in GitHub Desktop.
Simple SSL Koa JS server (HTTPS for Localhost)
const Koa = require('koa');
const path = require('path');
const serve = require('koa-static');
const http = require('http');
const https = require('https');
const fs = require('fs');
const commonDir = path.join(__dirname, '..', 'Client');
const app = new Koa();
// ============== Static files and html-templates
app.use(serve('.'));
app.use(serve(commonDir));
let appCallback = app.callback();
// ============== Server config
const config = {};
config.ports = {
http: 6009,
https: 7009
};
// ============ Path to openssl files
config.sslOptions = {
key: fs.readFileSync('ssl/key.pem', 'utf8').toString(),
cert: fs.readFileSync('ssl/cert.pem', 'utf8').toString(),
};
// ============== HTTP Server
try {
const httpServer = http.createServer(appCallback);
httpServer
.listen(config.ports.http, function(err) {
if (!!err) {
console.error('HTTP server FAIL: ', err, (err && err.stack));
}
else {
console.log(`${new Date().toLocaleString()} - HTTP listening on port ${config.ports.http}`);
}
});
}
catch (ex) {
console.error('Failed to start HTTP server\n', ex, (ex && ex.stack));
}
// ============== HTTPS Server
try {
const httpsServer = https.createServer(config.sslOptions, appCallback);
httpsServer
.listen(config.ports.https, function(err) {
if (!!err) {
console.error('HTTPS server FAIL: ', err, (err && err.stack));
}
else {
console.log(`${new Date().toLocaleString()} - HTTPS listening on port ${config.ports.https}`);
}
});
}
catch (ex) {
console.error('Failed to start HTTPS server\n', ex, (ex && ex.stack));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment