Created
June 30, 2015 07:45
-
-
Save allex/5b70db879e1938ee360e to your computer and use it in GitHub Desktop.
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
#!/bin/env node | |
/** | |
* A simple proxy for http request forwards. | |
* | |
* @author Allex Wang ([email protected]) | |
* | |
* GistID: 5b70db879e1938ee360e | |
* GistURL: https://gist.github.com/5b70db879e1938ee360e | |
*/ | |
var http = require('http') | |
, request = require('request') | |
, padLeft = function(s, len, c) { | |
s = '' + s; c = c || '0'; while (s.length < len) s = c + s; | |
return s | |
} | |
, ts = function(date) { | |
date = date || new Date() | |
return [date.getFullYear(), date.getMonth() + 1, date.getDay()].join('/') + ' ' + [padLeft(date.getHours(), 2), padLeft(date.getMinutes(), 2), padLeft(date.getSeconds(), 2), padLeft(date.getUTCMilliseconds(), 3)].join(':') | |
} | |
function log(s) { | |
if (s) { arguments[0] = '[' + ts() + '] ' + s } | |
console.log.apply(console, arguments) | |
} | |
function error(s) { | |
log(s); | |
} | |
function main() { | |
var port = 8080 | |
var server = http.createServer(function(req, res) { | |
var url = req.url | |
try { | |
var r = request(url) | |
r.on('end', function() { | |
log('\"%s %s\"', req.method, url, r.response.statusCode) | |
}) | |
req.pipe(r).pipe(res) | |
} catch (e) { | |
var msg = 'fatal: ' + e.message | |
res.writeHead(500) | |
res.end(msg) | |
error(msg) | |
} | |
}) | |
process.title = 'http-proxy' | |
process.on('uncaughtException', error) | |
server.listen(port); | |
log('Proxy server running on port %s.', port) | |
} | |
main() | |
// vim: set fdm=marker ts=2 sw=2 sts=2 tw=85 et : |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment