Skip to content

Instantly share code, notes, and snippets.

@Eronana
Created October 1, 2018 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Eronana/20211fbcd4c6ab9f8c633ec0fc6b6831 to your computer and use it in GitHub Desktop.
Save Eronana/20211fbcd4c6ab9f8c633ec0fc6b6831 to your computer and use it in GitHub Desktop.
a simple reverse proxy server with http proxy
const http = require('http');
const PROXY_PASS = 'http://www.google.com';
const HTTP_PROXY_PORT = 8888;
const HTTP_PROXY_HOST = '127.0.0.1';
const getOptions = (request) => ({
hostname: HTTP_PROXY_HOST,
port: HTTP_PROXY_PORT,
path: PROXY_PASS + request.url,
headers: request.headers,
method: request.method,
});
http.createServer().on('request', (request, response) => {
request.pipe(http.request(getOptions(request), (res) => {
response.writeHead(res.statusCode, res.headers);
res.pipe(response);
}));
}).on('upgrade', (request, socket) => {
http.request(getOptions(request)).on('upgrade', (res, sock) => {
const CRLF = '\r\n'
const headers = res.rawHeaders.map((header, i) => header + (i & 1 ? CRLF : ': ')).join('');
const head = `HTTP/${res.httpVersion} ${res.statusCode} ${res.statusMessage}${CRLF}${headers}${CRLF}`;
socket.write(head);
socket.pipe(sock).pipe(socket);
}).end();
}).listen(80, '0.0.0.0');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment