Skip to content

Instantly share code, notes, and snippets.

@switer
Forked from bnoordhuis/http-and-https-proxy.js
Created May 20, 2016 06:44
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 switer/0473701093d2d8647579a2432140eb4e to your computer and use it in GitHub Desktop.
Save switer/0473701093d2d8647579a2432140eb4e to your computer and use it in GitHub Desktop.
A node.js proxy that accepts HTTP and HTTPS traffic on the same port.
var fs = require('fs');
var net = require('net');
var http = require('http');
var https = require('https');
var httpAddress = '/path/to/http.sock';
var httpsAddress = '/path/to/https.sock';
fs.unlinkSync(httpAddress);
fs.unlinkSync(httpsAddress);
var httpsOptions = {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem')
};
net.createServer(tcpConnection).listen(8000);
http.createServer(httpConnection).listen(httpAddress);
https.createServer(httpsOptions, httpsConnection).listen(httpsAddress);
function tcpConnection(conn) {
conn.once('data', function(buf) {
// A TLS handshake record starts with byte 22.
var address = (buf[0] === 22) ? httpsAddress : httpAddress;
var proxy = net.createConnection(address, function() {
proxy.write(buf);
conn.pipe(proxy).pipe(conn);
});
});
}
function httpConnection(req, res) {
res.writeHead(200, { 'Content-Length': '4' });
res.end('HTTP');
}
function httpsConnection(req, res) {
res.writeHead(200, { 'Content-Length': '5' });
res.end('HTTPS');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment