Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(proxy): add proxy action #12

Merged
merged 4 commits into from
Jul 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions packages/svrx/__tests__/spec/svrx.plugin.proxy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
const supertest = require('supertest');
const { createServer } = require('../util');

describe('Proxy Action', async () => {
const PROXY_SERVER = 'http://localhost:9003';
const PROXY_SERVER_HTTPS = 'https://localhost:9004';
const svrx = createServer({
plugins: [
{
name: 'action-test',
inplace: true,
hooks: {
async onCreate({ router }) {
const { route } = router;
route(({ get }) => {
get('/api(.*)').to.proxy(PROXY_SERVER);
get('/origin/api/test').to.proxy(PROXY_SERVER, {
changeOrigin: true,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changeOrigin 建议作为默认选择?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

一般changeOrigin还是默认false的吧,它只对 name-based virtual site 有用

});
get('/origin/api/noset').to.proxy(PROXY_SERVER);
get('/rewrite/api(.*)').to.proxy(PROXY_SERVER, {
xuchaoying marked this conversation as resolved.
Show resolved Hide resolved
pathRewrite: {
'^/rewrite/api': '/api',
},
});
get('/secure/api/test').to.proxy(PROXY_SERVER_HTTPS, {
secure: false,
});
get('/secure/api/noset').to.proxy(PROXY_SERVER_HTTPS);
get('/dynamic/host/:port').to.proxy('http://localhost:{port}');
});
},
},
},
],
});
const proxyServer = createServer({
port: 9003,
plugins: [
{
name: 'proxy-action-test',
inplace: true,
hooks: {
async onCreate({ router }) {
const { route } = router;

route(({ get }) => {
get('/api(.*)').to.send('proxied');
get('/origin/api(.*)').to.handle((ctx) => {
if (ctx.request.headers.host === 'localhost:9003') {
ctx.body = 'changeOrigin proxied';
}
});
get('/dynamic/host/:port').to.send('dynamic proxied');
});
},
},
},
],
});
const proxyServerHttps = createServer({
port: 9004,
https: true,
plugins: [
{
name: 'proxy-action-test',
inplace: true,
hooks: {
async onCreate({ router }) {
const { route } = router;
route(({ get }) => {
get('/secure/api(.*)').to.send('secure proxied');
});
},
},
},
],
});

let agent;
before((done) => {
Promise.all([
svrx.setup(),
new Promise(resolve => proxyServer.start(resolve)),
new Promise(resolve => proxyServerHttps.start(resolve)),
]).then(() => {
agent = supertest(svrx.callback());
done();
});
});
after((done) => {
proxyServer.close();
proxyServerHttps.close();
done();
});

it('should proxy path to a target server', () => agent
.get('/api/test')
.expect('proxied'));

it('should change the host header when set changeOrigin to true', () => agent
.get('/origin/api/test')
.expect('changeOrigin proxied'));

it('should not change the host header when not set changeOrigin', () => agent
.get('/origin/api/noset')
.expect(404));

it('should rewrite the path after proxy', () => agent
.get('/rewrite/api/test')
.expect('proxied'));


it('should receive ERROR from a https server without a valid SSL certificate', () => agent
.get('/secure/api/noset')
.expect(500)); // Internal Server Error: self signed certificate

it('should work after set secure to false with server that has no valid SSL certificate', () => agent
.get('/secure/api/test')
.expect('secure proxied'));

it('should work when set a dynamic target hostname', () => agent
.get('/dynamic/host/9003')
.expect('dynamic proxied'));
});
26 changes: 23 additions & 3 deletions packages/svrx/lib/plugin/svrx-plugin-proxy/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ const libUrl = require('url');
const _ = require('lodash');
const micromatch = require('micromatch');
const { logger } = require('svrx-util');
const required = require('requires-port');
const { gunzip } = require('../../util/gzip');
const { isHtmlType, isRespGzip, getBody } = require('../../util/helper');
const {
isHtmlType, isRespGzip, getBody, simpleRender,
} = require('../../util/helper');
const { PRIORITY } = require('../../constant');

const BLOCK_RESPONSE_HEADERS = ['content-security-policy', 'transfer-encoding'];
Expand Down Expand Up @@ -41,6 +44,10 @@ const rewritePath = (path, rules) => {
return path;
};

function hasPort(host) {
return host.indexOf(':') >= 0;
}

async function proxy({ proxyRule, ctx }) {
const {
target, pathRewrite, changeOrigin, secure = true,
Expand All @@ -50,7 +57,11 @@ async function proxy({ proxyRule, ctx }) {
const { headers } = ctx;
const body = await getBody(ctx);

headers.host = changeOrigin ? urlObj.hostname : headers.host;
if (changeOrigin) {
headers.host = required(urlObj.port, urlObj.protocol) && !hasPort(urlObj.host)
? `${urlObj.host}:${urlObj.port}`
: urlObj.host;
}

const options = {
method: ctx.method,
Expand Down Expand Up @@ -81,7 +92,7 @@ module.exports = {
proxy,
priority: PRIORITY.PROXY,
hooks: {
async onCreate({ middleware, config }) {
async onCreate({ middleware, config, router }) {
const proxyConfig = config.get('proxy');
if (proxyConfig) {
if (_.isArray(proxyConfig)) {
Expand Down Expand Up @@ -109,6 +120,15 @@ module.exports = {
return next();
},
});

// add proxy action
router.action('proxy', (target, options = {}) => async (ctx) => {
const proxyRule = {
target: simpleRender(target, ctx.params),
...options,
};
await proxy({ proxyRule, ctx });
});
},

async onRoute(ctx, next, { config }) {
Expand Down
Loading