Skip to content

Instantly share code, notes, and snippets.

@peisenmann
Created February 5, 2016 16:20
Show Gist options
  • Save peisenmann/4f3daa869790036aae1d to your computer and use it in GitHub Desktop.
Save peisenmann/4f3daa869790036aae1d to your computer and use it in GitHub Desktop.
Gulp Serve task with proxy
var gulp = require('gulp');
var browserSync = require('browser-sync');
var httpProxy = require('http-proxy');
var chalk = require('chalk');
var localhostPort = 9000;
var proxyConfig = {
services: {
host1: { address: 'http://localhost:8080' },
host2: { address: 'http://localhost:8081' }
}
};
var proxies = {};
for (var serviceName in proxyConfig.services) {
if (proxyConfig.services.hasOwnProperty(serviceName)) {
var serviceConfig = proxyConfig.services[serviceName];
proxies[serviceName] = makeProxy(serviceName, serviceConfig.address, serviceConfig.opts);
}
}
function makeProxy(pathKey, url, opts) {
var proxy = {
url: url,
opts: opts || {},
pathKey: pathKey + '/',
server: httpProxy.createProxyServer({
target: url
})
};
proxy.server.on('error', function(error, req, res) {
console.error(chalk.red('ERROR on proxy ' + pathKey), proxy);
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end(JSON.stringify(error));
console.error(chalk.red('[Proxy]'), error);
});
return proxy;
}
// this task utilizes the browsersync plugin
// to create a dev server instance
// at http://localhost:9000
gulp.task('serve', ['build'], function(done) {
// List all the proxies in the console
console.info('[' + chalk.gray('serve.js') + '] ' + chalk.bold('Proxies:'));
for (var p in proxies) {
if (proxies.hasOwnProperty(p)) {
var proxy = proxies[p];
console.info('[' + chalk.gray('serve.js') + '] ' + chalk.magenta('http://localhost:' + localhostPort + '/' + proxy.pathKey), '->', chalk.cyan(proxy.url + '/' + (proxy.opts.removePrefix ? '' : proxy.pathKey)));
}
}
// Actually start the proxy server
browserSync({
open: false,
port: localhostPort,
server: {
baseDir: ['.'],
middleware: function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
for (var i in proxies) {
if (proxies.hasOwnProperty(i) && req.url.indexOf(proxies[i].pathKey) !== -1) {
var proxy = proxies[i];
if (proxy.opts.removePrefix) {
req.url = req.url.replace(new RegExp(i + "\/?", "i"), "");
}
//console.log("Using Proxy: " + i + " for " + req.url);
proxy.server.web(req, res);
return;
}
}
next();
}
}
}, done);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment