Skip to content

Instantly share code, notes, and snippets.

@geta6
Created December 7, 2012 02:35
Show Gist options
  • Save geta6/4230292 to your computer and use it in GitHub Desktop.
Save geta6/4230292 to your computer and use it in GitHub Desktop.
clustering proxy server
{
"name": "ProxyServer",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "NODE_ENV=production forever start -c coffee proxyserver.coffee",
"stop": "forever stop proxyserver.coffee"
},
"dependencies": {
"http-proxy": "*",
"underscore": "*"
}
}
#!/usr/bin/env coffee
###
Copyright (c) 2012 geta6
http://www.geta6.net/
Global Requirement:
forever
Scripts:
init : npm install
start : npm start
stop : npm stop
restart : npm restart
###
_ = require 'underscore'
cluster = require 'cluster'
cpunums = (require 'os').cpus().length
http = require 'http'
proxy = require 'http-proxy'
if cluster.isMaster
workers = {}
killall = (msg) ->
return (msg) ->
console.error "Killing with received #{msg}"
_.each workers, (worker) ->
worker.kill()
console.info "Worker died #{worker.pid}"
console.error "Shutting down master process."
process.exit 1
for i in [0...cpunums]
worker = cluster.fork()
workers[worker.pid] = worker
process.on 'uncaughtException', killall 'uncaughtException'
process.on 'exit', killall 'exit'
cluster.on 'death', (worker, code, signal) ->
cluster.fork()
console.log "Worker #{worker.process.pid} died"
else
server = proxy.createServer (req, res, proxy) ->
switch req.headers.host
when 'hoge.example.com' then port = 3030
when 'fuga.example.com' then port = 3031
when 'poyo.example.com' then port = 3032
else port = 0
if port > 3000
proxy.proxyRequest req, res,
host: req.headers.host
port: port
else
res.writeHead 404
res.end()
server.listen 3000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment