-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (51 loc) · 2.03 KB
/
index.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
import https from 'node:https';
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import express from 'express';
import proxy from 'express-http-proxy';
import rewrite from 'express-urlrewrite';
import yaml from 'js-yaml';
export default function gateway(configPath) {
const server = {};
configPath = configPath || process.env.NANO_GATEWAY_CONFIG || 'config.yml';
const config = yaml.load(fs.readFileSync(configPath, 'utf8'));
const app = express().disable('x-powered-by');
process.chdir(path.dirname(configPath));
function auth(req, res, next) {
const apiKey = req.headers.authorization || req.query.apiKey;
if (apiKey && apiKey === config.apiKey) {
return next();
}
const error = 'Unauthorized';
res.status(401, error);
next(error);
}
for (const [name, service] of Object.entries(config.services)) {
console.log(`service: ${name} at ${service.path}`);
const routeConfig = [
service.path,
service.auth || (service.auth === undefined && config.auth) ? auth : undefined,
service.rewrite ? rewrite(service.path, service.rewrite) : undefined,
proxy(service.url)
];
app.all(...routeConfig.filter(Boolean));
}
function showAddress(type) {
const bound = server[type].address();
console.log(`| ${type}://${bound.address}:${bound.port}`);
}
const pkg = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
console.log(`nano-gateway v${pkg.version} started at:`);
if (config.http || !config.https) {
server.http = app.listen(config.http.port || 8080, config.http.host, showAddress.bind(this, 'http'));
}
if (config.https && config.https.key && config.https.cert) {
const key = fs.readFileSync(config.https.key, 'utf8');
const cert = fs.readFileSync(config.https.cert, 'utf8');
const ca = config.https.ca ? fs.readFileSync(config.https.ca, 'utf8') : undefined;
server.https = https
.createServer({ key, cert, ca }, app)
.listen(config.https.port || 8443, showAddress.bind(this, 'https'));
}
}