[6a3a178] | 1 | var _ = require('lodash')
|
---|
| 2 | var logger = require('./logger').getInstance()
|
---|
| 3 |
|
---|
| 4 | module.exports = {
|
---|
| 5 | init: init,
|
---|
| 6 | getHandlers: getProxyEventHandlers
|
---|
| 7 | }
|
---|
| 8 |
|
---|
| 9 | function init(proxy, opts) {
|
---|
| 10 | var handlers = getProxyEventHandlers(opts)
|
---|
| 11 |
|
---|
| 12 | _.forIn(handlers, function(handler, eventName) {
|
---|
| 13 | proxy.on(eventName, handlers[eventName])
|
---|
| 14 | })
|
---|
| 15 |
|
---|
| 16 | logger.debug('[HPM] Subscribed to http-proxy events: ', _.keys(handlers))
|
---|
| 17 | }
|
---|
| 18 |
|
---|
| 19 | function getProxyEventHandlers(opts) {
|
---|
| 20 | // https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events
|
---|
| 21 | var proxyEvents = [
|
---|
| 22 | 'error',
|
---|
| 23 | 'proxyReq',
|
---|
| 24 | 'proxyReqWs',
|
---|
| 25 | 'proxyRes',
|
---|
| 26 | 'open',
|
---|
| 27 | 'close'
|
---|
| 28 | ]
|
---|
| 29 | var handlers = {}
|
---|
| 30 |
|
---|
| 31 | _.forEach(proxyEvents, function(event) {
|
---|
| 32 | // all handlers for the http-proxy events are prefixed with 'on'.
|
---|
| 33 | // loop through options and try to find these handlers
|
---|
| 34 | // and add them to the handlers object for subscription in init().
|
---|
| 35 | var eventName = _.camelCase('on ' + event)
|
---|
| 36 | var fnHandler = _.get(opts, eventName)
|
---|
| 37 |
|
---|
| 38 | if (_.isFunction(fnHandler)) {
|
---|
| 39 | handlers[event] = fnHandler
|
---|
| 40 | }
|
---|
| 41 | })
|
---|
| 42 |
|
---|
| 43 | // add default error handler in absence of error handler
|
---|
| 44 | if (!_.isFunction(handlers.error)) {
|
---|
| 45 | handlers.error = defaultErrorHandler
|
---|
| 46 | }
|
---|
| 47 |
|
---|
| 48 | // add default close handler in absence of close handler
|
---|
| 49 | if (!_.isFunction(handlers.close)) {
|
---|
| 50 | handlers.close = logClose
|
---|
| 51 | }
|
---|
| 52 |
|
---|
| 53 | return handlers
|
---|
| 54 | }
|
---|
| 55 |
|
---|
| 56 | function defaultErrorHandler(err, req, res) {
|
---|
| 57 | var host = req.headers && req.headers.host
|
---|
| 58 | var code = err.code
|
---|
| 59 |
|
---|
| 60 | if (res.writeHead && !res.headersSent) {
|
---|
| 61 | if (/HPE_INVALID/.test(code)) {
|
---|
| 62 | res.writeHead(502)
|
---|
| 63 | } else {
|
---|
| 64 | switch (code) {
|
---|
| 65 | case 'ECONNRESET':
|
---|
| 66 | case 'ENOTFOUND':
|
---|
| 67 | case 'ECONNREFUSED':
|
---|
| 68 | res.writeHead(504)
|
---|
| 69 | break
|
---|
| 70 | default:
|
---|
| 71 | res.writeHead(500)
|
---|
| 72 | }
|
---|
| 73 | }
|
---|
| 74 | }
|
---|
| 75 |
|
---|
| 76 | res.end('Error occured while trying to proxy to: ' + host + req.url)
|
---|
| 77 | }
|
---|
| 78 |
|
---|
| 79 | function logClose(req, socket, head) {
|
---|
| 80 | // view disconnected websocket connections
|
---|
| 81 | logger.info('[HPM] Client disconnected')
|
---|
| 82 | }
|
---|