You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.1 KiB
JavaScript

const next = require('next');
express = require('express');
httpProxy = require('http-proxy');
NodeCache = require( "node-cache" );
dev = process.env.NODE_ENV == 'development';
cacheDefaultTTL = dev ? 60 : 300;
myCache = new NodeCache( {stdTTL: cacheDefaultTTL, checkperiod: cacheDefaultTTL+1} );
port = process.env.PORT || 3000;
host = dev ? `http://localhost:${port}` : `http://on.loki`;
app = next({ dev });
handle = app.getRequestHandler();
proxy = httpProxy.createProxyServer({});
app.prepare().then(() => {
express()
.use(async function(req, res) {
var subdomain = req.headers.host;
if(subdomain == "on.loki" || subdomain == `localhost:${port}`) {
handle(req, res);
return;
}
let resp, data;
data = myCache.get(subdomain);
if(data == undefined) {
try {
resp = await fetch(
host + `/api/resolve`,
{
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ subdomain: subdomain.replace(".on.loki", "").replace(`:${port}`, "") }),
}
);
data = await resp.json();
} catch (error) {
res.send("Internal error");
console.log(error);
return;
}
myCache.set(subdomain, data);
}
if(data.ok) {
if(data.redirect == 1) {
res.redirect("http://" + data.address + ".loki" + req.originalUrl);
}else{
try {
proxy.web(req, res, { target: "http://" + data.address + ".loki" });
}catch(error) {
console.log(error);
res.send("Error proxying request.");
return
}
}
}else{
res.send(data.error);
}
})
.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on ${host}`);
})
}).catch(err => {
console.log('Error:::::', err);
})