vagusX/koa-proxies

Dynamic proxy target

feegloo opened this issue · 3 comments

I need to set different target depending on some header in request.

Example:

ctx.headers['foo'] === 'bar' ==> target: 'http://localhost:3000/'
ctx.headers['foo'] === 'baz' ==> target: 'http://localhost:3001/'

Hello @feegloo,
I have a workaround, set different target in url path:

const Koa = require('koa');
const proxy = require('koa-proxies');
const app = new Koa();

const targets = {
    bar: 'http://localhost:3000/',
    baz: 'http://localhost:3001/'
};

app.use(proxy('/proxy/:target/', function(params) {
    return {
        target: targets[params.target] || 'http://localhost:8080',
        rewrite: p => p.replace(/^\/proxy\/\w+\//, '/'),
        changeOrigin: true,
        logs: true
    };
}));

app.listen(8080);

then we can call:

Refs: https://github.com/vagusX/koa-proxies/blob/master/index.js#L33
because the options can be a function.

Hello @wuliupo, @feegloo,
in our case it is also not possible to distinguish the target by URL parameters.
For out local environment we use the referer header to route to either local server or remote server.

Simply passing the context to the mentioned function a1d3e19 allows to create dynamic target based on the context content.

I created pull request #52 for that.

The issue is taking too long I have to fork and rewrite it for supporting router config https://github.com/luxueyan/koa-proxies