0

I'm using hapi.js for serving html content in an application. Now I needed to proxy some services which may use websockets.

Here is the working code that proxies http://localhost:4000 in http://localhost:5000/my/app :

hapi = require "hapi" 
http-proxy = require 'http-proxy'
server = hapi.create-server 5000 

server.route do
  method: '*'
  path: '/my/app/{f*}'
  handler: 
    proxy:
      map-uri: (request, callback) -> 
        resourceUri = request.url.path.replace('/my/app/', '/')
        url = 'http://localhost:4000' + resourceUri
        console.log 'url: ', url
        callback(null,url);
      pass-through: true
      xforward: true

ws-proxy = http-proxy.create-proxy-server do
  target:'http://localhost:4000/socket.io/'

ws-proxy.on 'error', (err, req, res) !-> 
  console.log "error caught: ", err#, req

server.start !->
  server.listener.on 'upgrade', (req, socket, head) !->
    console.log "upgrade dedected"
    ws-proxy.ws(req, socket, head)
    #console.log req, socket, head
  console.log 'Proxy started @ ' + server.info.uri

Auto generated Javascript code is:

// Generated by LiveScript 1.3.1
(function(){
  var hapi, httpProxy, server, wsProxy;
  hapi = require("hapi");
  httpProxy = require('http-proxy');
  server = hapi.createServer(5000);
  server.route({
    method: '*',
    path: '/my/app/{f*}',
    handler: {
      proxy: {
        mapUri: function(request, callback){
          var resourceUri, url;
          resourceUri = request.url.path.replace('/my/app/', '/');
          url = 'http://localhost:4000' + resourceUri;
          console.log('url: ', url);
          return callback(null, url);
        },
        passThrough: true,
        xforward: true
      }
    }
  });
  wsProxy = httpProxy.createProxyServer({
    target: 'http://localhost:4000/socket.io/'
  });
  wsProxy.on('error', function(err, req, res){
    console.log("error caught: ", err);
  });
  server.start(function(){
    server.listener.on('upgrade', function(req, socket, head){
      console.log("upgrade dedected");
      wsProxy.ws(req, socket, head);
    });
    console.log('Proxy started @ ' + server.info.uri);
  });
}).call(this);

Is there any way to achieve same goal without hardcoding the websocket address of http://localhost:4000/socket.io/?

ceremcem
  • 3,900
  • 4
  • 28
  • 66

1 Answers1

0

So from reading the code you always proxy to http://localhost:4000/socket.io/, however you want this to be dynamic?

You could pass the server you wish to proxy to in the initial request as a parameter? You could potentially pass this in the protocol field of the WebSocket constructor. Then read this on the servers on-open event.

Sphvn
  • 5,247
  • 8
  • 39
  • 57