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.

51 lines
1.0 KiB

4 years ago
  1. var _ = require('lodash')
  2. var logger = require('./logger.js').getInstance()
  3. module.exports = {
  4. getTarget: getTarget
  5. }
  6. function getTarget(req, config) {
  7. var newTarget
  8. var router = config.router
  9. if (_.isPlainObject(router)) {
  10. newTarget = getTargetFromProxyTable(req, router)
  11. } else if (_.isFunction(router)) {
  12. newTarget = router(req)
  13. }
  14. return newTarget
  15. }
  16. function getTargetFromProxyTable(req, table) {
  17. var result
  18. var host = req.headers.host
  19. var path = req.url
  20. var hostAndPath = host + path
  21. _.forIn(table, function(value, key) {
  22. if (containsPath(key)) {
  23. if (hostAndPath.indexOf(key) > -1) {
  24. // match 'localhost:3000/api'
  25. result = table[key]
  26. logger.debug('[HPM] Router table match: "%s"', key)
  27. return false
  28. }
  29. } else {
  30. if (key === host) {
  31. // match 'localhost:3000'
  32. result = table[key]
  33. logger.debug('[HPM] Router table match: "%s"', host)
  34. return false
  35. }
  36. }
  37. })
  38. return result
  39. }
  40. function containsPath(v) {
  41. return v.indexOf('/') > -1
  42. }