Created
October 1, 2018 09:35
-
-
Save Eronana/20211fbcd4c6ab9f8c633ec0fc6b6831 to your computer and use it in GitHub Desktop.
a simple reverse proxy server with http proxy
This file contains 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
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