You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.0 KiB

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