Last active
March 4, 2020 15:10
-
-
Save Xmerr/45c6b62ca5af32b9b51edce4462990f7 to your computer and use it in GitHub Desktop.
Koa Subdomain Router
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
host: "http://localhost", | |
apps: [ | |
{ | |
name: "strapi", | |
port: 3537, | |
redirect: "/admin", | |
sub: "admin" | |
}, | |
{ | |
name: "apis", | |
port: 3537, | |
sub: "api" | |
}, | |
{ | |
name: "obsMaster", | |
port: 8675, | |
sub: "obs" | |
}, | |
{ | |
name: "io", | |
port: 3501, | |
sub: "io" | |
}, | |
{ | |
name: "ui", | |
port: 3500, | |
sub: "*" | |
} | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Koa = require('koa'); | |
const Subdomain = require('koa-subdomain'); | |
const Router = require('koa-router'); | |
const proxy = require('koa-proxy'); | |
const { apps, host } = require('config'); | |
const app = new Koa(); | |
const subdomain = new Subdomain(); | |
const createRouter = ({ port, redirect, sub }) => { | |
const router = new Router(); | |
if(redirect) { | |
router.all('*', ctx => { | |
ctx.redirect(`${host}:${port}${redirect}/`); | |
}) | |
} else { | |
router.all('*', proxy({ | |
host: `${host}:${port}/`, | |
jar: true | |
})); | |
} | |
subdomain.use(sub, router.routes()); | |
}; | |
apps.forEach(app => createRouter(app)); | |
app.use(subdomain.routes()); | |
app.listen(80); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment