Created
September 30, 2015 22:07
-
-
Save ben-bradley/b22241775b8efc47b932 to your computer and use it in GitHub Desktop.
hapiProxyClass
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
let Hapi = require('hapi'), | |
h2o2 = require('h2o2'); | |
let server = new Hapi.Server(); | |
let proxies = {}; | |
server.connection({ | |
port: 3000 | |
}); | |
server.route({ | |
method: 'get', | |
path: '/proxy/{name}', | |
handler: (request, reply) => { | |
let name = request.params.name, | |
proxy = proxies[name] = new Proxy(name); | |
proxy.start((err) => { | |
if (err) | |
return reply({err}); | |
reply('started!'); | |
}); | |
} | |
}); | |
server.route({ | |
method: 'get', | |
path: '/proxy/{name}/log', | |
handler: (request, reply) => { | |
let name = request.params.name, | |
proxy = proxies[name]; | |
reply(proxy.app.log); | |
} | |
}); | |
server.start((err) => { | |
if (err) | |
throw new Error(err); | |
console.log('listening...'); | |
}); | |
class Proxy extends Hapi.Server { | |
constructor(name, options) { | |
super((options || {}).hapi); | |
if (!options) | |
options = { proxy: {} }; | |
this.connection({ | |
port: options.proxy.port || 4000 | |
}); | |
this.register({ | |
register: h2o2 | |
}, (err) => { | |
if (err) | |
throw new Error(err); | |
}); | |
let log = this.app.log = []; | |
this.route({ | |
method: '*', | |
path: '/{p*}', | |
handler: { | |
proxy: { | |
host: options.proxy.host || 'www.google.com', | |
port: options.proxy.port || 443, | |
protocol: options.proxy.protocol || 'https', | |
// pass headers both directions | |
passThrough: options.proxy.passThrough || true, | |
// pass cookies | |
localStatePassThrough: options.proxy.localStatePassThrough || true, | |
onResponse: (err, res, request, reply, settings, ttl) => { | |
log.push({ | |
request: request.headers, | |
response: res.headers | |
}); | |
reply(res); // pass it through | |
} | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment