Created
July 6, 2018 07:17
-
-
Save leshniak/6a7fe1b07c00255215739fa4e30fe252 to your computer and use it in GitHub Desktop.
Simple HTTP(S) node proxy
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
const httpProxy = require('http-proxy'); | |
const http = require('http'); | |
const net = require('net'); | |
const hostRegExp = /^(?<host>[^:]+)(:(?<port>[0-9]+))?$/; | |
const proxy = httpProxy.createProxyServer({}); | |
const server = http.createServer(function (req, res) { | |
const { protocol, host } = new URL(req.url); | |
const target = `${protocol}//${host}`; | |
console.log('Proxy HTTP request for:', target); | |
proxy.web(req, res, { | |
target, | |
// selfHandleResponse: true, // useful for stubbing along with proxyRes event | |
}); | |
}); | |
proxy.on('error', (err, req, res) => { | |
console.log('proxy error', err); | |
res.end(); | |
}); | |
server.addListener('connect', (req, socket, head) => { | |
const url = new URL(`ssl://${req.url}`); | |
const host = url.hostname; | |
const port = parseInt(url.port || 443, 10); | |
const proxySocket = new net.Socket(); | |
console.log('Proxying HTTPS request for:', host, port); | |
proxySocket.connect(port, host, () => { | |
proxySocket.write(head); | |
socket.write(`HTTP/${req.httpVersion} 200 Connection established\r\n\r\n`); | |
}); | |
proxySocket.on('data', (chunk) => { | |
socket.write(chunk); | |
}); | |
proxySocket.on('end', () => { | |
socket.end(); | |
}); | |
proxySocket.on('error', () => { | |
socket.write(`HTTP/${req.httpVersion} 500 Connection error\r\n\r\n`); | |
socket.end(); | |
}); | |
socket.on('data', (chunk) => { | |
proxySocket.write(chunk); | |
}); | |
socket.on('end', () => { | |
proxySocket.end(); | |
}); | |
socket.on('error', () => { | |
proxySocket.end(); | |
}); | |
}); | |
server.listen(8081); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment