function start() { debugging = nconf.get('debugging'); routing.loadRoutingTable(nconf, routingTable); server = httpProxy.createServer(function (req, res, proxy) { var buffer = httpProxy.buffer(req); var destinationHosts = routingTable[req.headers.host]; if (destinationHosts != null && destinationHosts.length > 0) { var destinationHost = destinationHosts[Math.floor(Math.random() * destinationHosts.length)]; log(req.url + " => " + destinationHost); req.headers.host = destinationHost; if (destinationHost != null) { proxy.proxyRequest(req, res, { host: destinationHost, port: 80, buffer: buffer }); } else { log("Host not found!"); internalServerError(res) } } else { log("No destination hosts!"); internalServerError(res) } }).listen(80); server.proxy.on('proxyError', function (err, req, res) { internalServerError(res); }); }
.then(credentials => { const httpsServer = httpProxy.createServer({ https: { SNICallback: (hostname, callback) => { callback(null, credentials.getCredentialsContext(hostname)); }, key: ssl.key, cert: ssl.cert, ca: ssl.ca } }, function(req, res, proxy) { serve(req, res, proxy, config.lookup(req, 'https:')); }); httpsServer.on('upgrade', (req, socket, head)=> { httpServer.proxy.proxyWebSocketRequest(req, socket, head, config.lookup(req, 'https:')); }); httpServer.listen(config.getPort('https'), ()=> { util.log('HTTPS Listening ons 0.0.0.0:' + config.getPort('https')); }); })
this.rebuildRouter(function(err, router) { if (err) { logger.error('Error building router') logger.error(err); } else { self.options.router = router; self.proxyServer = httpProxy.createServer(self.options).listen(config.proxySPort, config.bindIp); self.proxyServer.proxy.on('proxyError', function(err, req, res) { var host = req.headers.host || 'This site' logger.error('Error proxying request') logger.error(err) var filename = path.join(path.normalize(__dirname+'/..'), 'config', 'error.jade') var html = jade.renderFile(filename, { companyName: config.companyName , logoUrl: config.logoUrl , cssUrl: config.cssUrl , host: host }) res.writeHead(200, { 'Content-Type': 'text/html'}) res.write(html) res.end() }) self.table = self.proxyServer.proxy.proxyTable; self.setup(); } });
.act(function(opts, agrs) { var http = require('http'), httpProxy = require('http-proxy'), routes = typeof opts.config === 'string' ? JSON.parse(FS.readFileSync(opts.config, 'utf8')) : opts.config, router = {}; for (var route in routes) { router[opts.host + route] = opts.bemhost + ':' + opts.bemport + routes[route]; } if (opts.root || opts.internal || opts.global) { var sys = require('sys'), exec = require('child_process').exec, puts = function(error, stdout, stderr) { sys.puts(stdout); }, root = (!opts.root || opts.root == 'cwd') ? process.cwd() : opts.root, bemPath = opts.internal ? PATH.resolve(__dirname, '../node_modules/bem/bin/bem') : (opts.global ? 'bem' : PATH.resolve(root, 'node_modules/bem/bin/bem')); console.log('BEM: ', bemPath + ' server -r ' + root + ' --host ' + opts.bemhost + ' -p ' + opts.bemport); exec(bemPath + ' server -r ' + root + ' --host ' + opts.bemhost + ' -p ' + opts.bemport , puts); } console.log('Your route table is'); console.log(router); console.log('Server is listening on port ' + opts.port + '. Point your browser to http://' + opts.host + (opts.port === 80 ? '' : (':' + opts.port)) + '/'); var options = { router: router }; var proxyServer = httpProxy.createServer(options); proxyServer.listen(opts.port); });
fs.readdir(nodeProxyDir, function(err, files) { if (err) { console.log('Error: ' + err); return; } for (var i = 0, ln = files.length, file, data; i < ln; i++) { file = files[i]; if (file.slice(-5) === '.json') { data = fs.readFileSync(nodeProxyDir + '/' + file, 'utf8'); data = JSON.parse(data); for (var name in data) { options["router"][name] = data[name]; } } } //create proxy server var server = httpProxy.createServer(options); //start proxy server server.listen(80, function() { console.log('Node Proxy Server started with options:', options); // Downgrade the process to run as the ubuntu group and user now that it's bound to privileged ports. process.setgid('ubuntu'); process.setuid('ubuntu'); }); });
Router.prototype.start = function() { var self = this; this.server = httpProxy.createServer(this.proxy_request.bind(this)); if (cluster.isMaster) { cluster.setupMaster({ silent : false, args : [process.argv[2]] }); for (var i = 0, j = CPU_COUNT.length; i < j; i++) { this.fork(); }; } else { this.setup_listeners(); this.setup_sweepers(); this.loadStatic(); this.server.listen(raft.config.get('router:http:port')); this.server.proxy.on('end', function(req, res) { res.timer.end = Date.now(); if (!req.droplet) return; req.droplet.usage.requests = req.droplet.usage.requests + 1; req.droplet.usage.upload = req.droplet.usage.upload + req.socket.bytesRead; req.droplet.usage.download = req.droplet.usage.download + req.socket.bytesWritten; droplet.log.log(self.gen_log_info(req, res, droplet)); }); }; };
var init = function (options) { options = options || { port: 8080 } var proxy = httpProxy.createServer({ target: 'http://'+hostIP+':10000' , ws: true }); proxy.on('proxyReq', request); proxy.on('proxyRes', response); proxy.on('error', function(err, req, res) { res.end(); }) var app = connect(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(transformerProxy(inject)); // , {match : /\.js([^\w]|$)/} app.use( function (req, res) { if (req.headers.host == hostIP+':3232') { console.log("porting to verth io"); proxy.web(req, res, { target: 'http://'+hostIP+':3232' }); } else { proxy.web(req, res, { target: 'http://'+hostIP+':10000' }); } req.on('end', function(){ setTimeout(function(){ keylogger = 0 }, 100) }) }); http.createServer(app).listen(options.port); }
exports.createServer = function createServer(options) { if (!options) options = {}; // Default options: var httpProxyOptions = { xforward: { enable: true // Append X-Forwarded-* headers } }; // Allow user to override defaults and add own options if (options.httpProxyOptions) { Object.keys(options.httpProxyOptions).forEach(function(option) { httpProxyOptions[option] = options.httpProxyOptions[option]; }); } var handler = getHandler(options); var server = httpProxy.createServer(httpProxyOptions, handler); // When the server fails, just show a 404 instead of Internal server error server.proxy.on('proxyError', function(err, req, res) { res.writeHead(404, {'Access-Control-Allow-Origin': '*'}); res.end('Not found because of proxy error: ' + err); }); return server; };
test('Streams can change the response size', function (t) { t.plan(1); http.createServer(function (req, res) { s = '<body><p>hi</p></body>'; res.setHeader('Content-length', '' + s.length); // All ASCII today res.end(s); }).listen(9001); var sizeChanger = { query: 'p', func: function (elem) { ws = elem.createWriteStream({outer: true}) ws.end('<p>A larger paragraph</p>'); } }; httpProxy.createServer( require('../')(null, [sizeChanger]), 9001, 'localhost' ).listen(8001); http.get('http://localhost:8001', function (res) { var str = ''; // yeah well it's all ASCII today. res.on('data', function (data) { str += data; console.log("'data'", '' + data); }); res.on('end', function () { t.equal(str, '<body><p>A larger paragraph</p></body>'); t.end(); }); }); });
grunt.registerTask("cors-server", "Runs a CORS proxy", function(){ var corsPort = arguments[0] || grunt.config("cors-server.port"); var couchUrl = grunt.option('couch-host') || grunt.config("cors-server.base"); grunt.log.writeln("Starting CORS server " + corsPort + " => " + couchUrl); cors_proxy.options = {target: couchUrl}; http_proxy.createServer(cors_proxy).listen(corsPort); });
function startServers(couchHost) { http_server.createServer().listen(HTTP_PORT); cors_proxy.options = {target: couchHost || COUCH_HOST}; http_proxy.createServer(cors_proxy).listen(CORS_PORT); console.log('Tests: http://127.0.0.1:' + HTTP_PORT + '/tests/test.html' + query); }
exports.start = function(options) { var options = options || {}; var port = options.port || 8003; var suffix = '/api/'; var proxy_options = { enable : { xforward: true }, changeOrigin: true }; httpProxy.createServer(proxy_options, function (req, res, proxy) { var parsed_url; var parsed_host; var parsed_port; req.url = req.url.replace(/\/api\//, ''); parsed_url = url.parse(req.url); parsed_host = parsed_url.host; parsed_port = parsed_url.port || 80; proxy.proxyRequest(req, res, { host: parsed_host, port: parsed_port }); }).listen(port, function() { console.log('Rest proxy listening on port ' + port); }); };
http.createServer(function(req, res) { var reqUrl = req.url; var from = reqUrl; var map = urlconfig.map; if (from) { log.info('[get]' + from); var to = utils.rewrite(map, from); if (from !== to) { log.info('[rewirte]' + from + '->' + to); if (!/^https?:\/\//.test(to)) { var contentType = mime.lookup(to); var buffer = fs.readFileSync(to); utils.setResponse(res, contentType, buffer); return; } return; } } var parsedUrl = url.parse(reqUrl); var proxy = httpProxy.createServer({ target: { host: parsedUrl.hostname, port: parsedUrl.port || 80 } }); proxy.proxyRequest(req, res); }).listen(config.port, function() {
exports.startServer = function(port, path) { var app = express(); // Configuration app.configure(function() { app.use(express.static(__dirname + "/_public")); }); app.configure("development", function() { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure("production", function() { app.use(express.errorHandler()); }); var proxiedPort = port + 1; app.listen(proxiedPort); var proxyConfigurations = configuration.proxy; var getMatchingConfig = function(req) { for (var i = 0; i < proxyConfigurations.length; i++) { var config = proxyConfigurations[i]; if (req.url.match(new RegExp("^" + config.url, "i"))) { return config; } } return null; }; httpProxy.createServer( function (req, res, proxy) { var target = { "host":"localhost", "port":proxiedPort }; var proxyConfig = getMatchingConfig(req); if (proxyConfig) { target["host"] = proxyConfig.host; target["port"] = proxyConfig.port; if (proxyConfig.rewrite_url) { req.url = proxyConfig.rewrite_url + req.url; proxy.proxyRequest(req, res, target); return; } if (!proxyConfig.keep_url) { req.url = req.url.slice(proxyConfig.url.length); } } proxy.proxyRequest(req, res, target); } ).listen(port); };