|
| 1 | +var http = require('http'), |
| 2 | + https = require('https'), |
| 3 | + url = require('url'), |
| 4 | + caronte = require('./caronte'), |
| 5 | + events = require('eventemitter2'), |
| 6 | + proxy = exports; |
| 7 | + |
| 8 | +/** |
| 9 | + * Creates the proxy server. |
| 10 | + * |
| 11 | + * Examples: |
| 12 | + * |
| 13 | + * caronte.createProxyServer({ .. }, 8000) |
| 14 | + * // => '{ web: [Function], ws: [Function] ... }' |
| 15 | + * |
| 16 | + * @param {Object} Options Config object passed to the proxy |
| 17 | + * |
| 18 | + * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests |
| 19 | + * |
| 20 | + * @api public |
| 21 | + */ |
| 22 | + |
| 23 | +proxy.createProxyServer = function createProxyServer(options) { |
| 24 | + if(!options) { |
| 25 | + throw new Error([ |
| 26 | + "`options` is needed and it must have the following layout:", |
| 27 | + " ", |
| 28 | + " { ", |
| 29 | + " target : <url string to be parsed with the url module> ", |
| 30 | + " forward: <url string to be parsed with the url module> ", |
| 31 | + " ssl : <object to be passed to https.createServer()> ", |
| 32 | + " ws : <true/false, if you want to proxy websockets> ", |
| 33 | + " xfwd : <true/false, adds x-forward headers> ", |
| 34 | + " } ", |
| 35 | + " ", |
| 36 | + "NOTE: `options.ws` and `options.ssl` are optional ", |
| 37 | + " either one or both `options.target` and ", |
| 38 | + " `options.forward` must exist " |
| 39 | + ].join("\n")); |
| 40 | + } |
| 41 | + |
| 42 | + ['target', 'forward'].forEach(function(key) { |
| 43 | + options[key] = url.parse(options[key]); |
| 44 | + }); |
| 45 | + |
| 46 | + return { |
| 47 | + __proto__: new events.EventEmitter2({ wildcard: true, delimiter: ':' }), |
| 48 | + web : caronte.createWebProxy(options), |
| 49 | + ws : caronte.createWsProxy(options), |
| 50 | + listen : function listen(port) { |
| 51 | + var server = options.ssl ? http.createServer(this.web) : https.createServer(options.ssl, this.web); |
| 52 | + |
| 53 | + if(options.ws) { |
| 54 | + server.on('upgrade', this.ws); |
| 55 | + } |
| 56 | + |
| 57 | + return server; |
| 58 | + } |
| 59 | + }; |
| 60 | +}; |
| 61 | + |
0 commit comments