coffeescript+nodejs实现http代理服务器支持get、post

http = require('http')
url = require('url')

http.globalAgent.maxSockets = 10240;

parseOpthons = (req) ->
	opt = {}
	url_info = url.parse(req.url)

	opt.host = url_info.host
	opt.hostname = url_info.hostname
	opt.path = url_info.path
	opt.port = 80
	opt.method = req.method
	opt.headers = req.headers
	console.log opt.method
	return opt

server = http.createServer (req, res) ->

	opt = parseOpthons(req)

	data = ""
	req.on 'data', (post_data_chunk) ->
		data = post_data_chunk

	req.on 'end', () ->
		if opt.method == "POST" 
			proxy_request.end(data)
		else
			proxy_request.end() 

	proxy_request = http.request opt, (p_res) ->
		headers = p_res.headers
		statusCode = p_res.statusCode
		res.writeHead(statusCode, headers)

		p_res.on 'data', (chunk) ->
			res.write(chunk, 'binary')

		p_res.on 'end', () ->
			res.end()

	responseHdr = () ->
		if proxy_request
		else
			proxy_request.abort() 

	timeoutHdr = () ->
		proxy_request.emit('req-timeout')

	proxy_request.on 'req-timeout', responseHdr

	proxy_request.on 'error', () ->
		clearTimeout(setTimeout(timeoutHdr, 5000)) 		

server.listen 8888

process.on 'uncaughtException', (err) ->
	console.log('LAST ERROR: Caught exception: ' + err)
	util.log(err.stack)

console.log "server start...."

相关推荐