Skip to content

Instantly share code, notes, and snippets.

@hartzis
Last active August 3, 2023 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save hartzis/ce191533d8579afe2481ddd5e2c6024a to your computer and use it in GitHub Desktop.
Save hartzis/ce191533d8579afe2481ddd5e2c6024a to your computer and use it in GitHub Desktop.
Restify proxy pattern using http-proxy. Uses restify server.pre() to setup a pattern to handle proxy requests before all middleware.
/*
* "restify": "^7.2.0",
* "http-proxy": "^1.17.0",
*
* The restify server will proxy requests that match keys in a `proxies` config.
*
*/
const restify = require('restify');
const httpProxy = require('http-proxy');
const proxiesConfig = {
'/proxy': {
url: 'http://www.proxiedService.com',
whitelist: {
GET: '/api/v1/users/'
}
}
};
/**
* Every key in proxies becomes a proxy path on the server
* ie. `/proxy` key becomes a path on the server - '/proxy'
*/
function setupProxies(proxies = {}) {
// Setup proxy server if we have proxies
const httpProxyServer = Object.keys(proxies).length > 0
? httpProxy.createProxyServer({})
: undefined;
return function proxiesMiddleware(req, res, next) {
if (httpProxyServer === undefined) {
return next();
}
const proxy = `/${req.url.split('/')[1]}`;
if (
(proxy in proxies) &&
proxies[proxy].whitelist &&
proxies[proxy].whitelist[method] &&
Array.isArray(proxies[proxy].whitelist[method]) &&
proxies[proxy].whitelist[method]
.some(path => req.url.startsWith(`${proxy}${path}`))
) {
req.url = req.url.substring(proxy.length);
// complete the actual proxy'ing of the request
httpProxyServer.web(req, res, {
target: proxies[proxy].url,
});
} else {
next();
}
};
};
const server = restify.createServer({
name: 'proxy-test',
});
/*
* Using server.pre() because it runs before all middleware.
* http://restify.com/docs/server-api/#pre
*/
server.pre(setupProxies(proxiesConfig));
const port = process.env.PORT || 3000;
server.listen(port);
console.log(`Server is listening on port ${port}`);
//.....
/*
* After starting the server you should be able to request to your proxy.
*
* $ curl http://localhost:3000/proxy/api/v1/users/1234
* Would proxy to - http://www.proxiedService.com/api/v1/users/1234
*
*/
@vasx93
Copy link

vasx93 commented Aug 3, 2023

Nice, do you maybe have an example of this in dockerized environment?

@hartzis
Copy link
Author

hartzis commented Aug 3, 2023

@vasx93 no i do not, that’s something i haven’t explored. please share if you do find something

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment