typicode / katon

(use hotel instead)
https://github.com/typicode/hotel
MIT License
683 stars 28 forks source link

Support location (path) proxy routing #80

Open dlee opened 9 years ago

dlee commented 9 years ago

I develop on a complex web app with many services, and most of these services are proxy routed via path (like nginx's location) rather than subdomain.

Would it be possible for katon to route different paths on a single domain to different upstream services?

typicode commented 9 years ago

Can you provide an example please? Not sure to understand.

dlee commented 9 years ago

For example, in nginx, you can proxy requests to the same domain to different upstream servers depending on URL path:

    location / {

      location ~ /api {
        proxy_pass $api_server;
      }

      location ~ ^/assets {
        proxy_pass $assets_server;
      }

      proxy_pass $app_server;
    }

Requests for /api/xyz will be proxied to $api_server, requests for /assets/pic.jpg will be proxied to $assets_server, and all other requests will be proxied to $app_server.

typicode commented 9 years ago

Thanks for the example. Unfortunately, katon doesn't support that.

But creating a simple proxy server could do the trick. I've not tested the code but it should give you the overall idea.

// proxy.js
var http = require('http')
var httpProxy = require('http-proxy')
var proxy = httpProxy.createProxyServer()

http.createServer(function(req, res) {
  // Extract id from /:id/*
  var arr = req.url.split('/')
  arr.shift()
  var id = arr.shift()

  // Reconstruct URL
  req.url = arr.join('/')

  // Proxy to http://:id.ka
  proxy.web(req, res, { target: 'http://' + id + '.ka'  })
}).listen(process.env.PORT)
~/proxy$ katon add 'nodemon proxy.js' --name my-project
~/api$ katon add 'cmd'

Requests to http://my-project.ka/api should then be proxied http://api.ka

For more information, see https://github.com/nodejitsu/node-http-proxy

Tell me if it doesn't work.