Skip to content

Instantly share code, notes, and snippets.

@Deityhub
Created March 23, 2021 19:43
Show Gist options
  • Save Deityhub/5742be28ff3f60c19021c1d69a72d402 to your computer and use it in GitHub Desktop.
Save Deityhub/5742be28ff3f60c19021c1d69a72d402 to your computer and use it in GitHub Desktop.
Create server handler for using the same port on the both http and https
function createServer(opts, handler) {
const server = net.createServer(socket => {
socket.once('data', buffer => {
// Pause the socket
socket.pause();
// Determine if this is an HTTP(s) request
const byte = buffer[0];
let protocol;
if (byte === 22) {
protocol = 'https';
} else if (32 < byte && byte < 127) {
protocol = 'http';
}
const proxy = server[protocol];
if (proxy) {
// Push the buffer back onto the front of the data stream
socket.unshift(buffer);
// Emit the socket to the HTTP(s) server
proxy.emit('connection', socket);
}
// As of NodeJS 10.x the socket must be
// resumed asynchronously or the socket
// connection hangs, potentially crashing
// the process. Prior to NodeJS 10.x
// the socket may be resumed synchronously.
process.nextTick(() => socket.resume());
});
});
server.http = http.createServer(handler);
server.https = https.createServer(options, handler);
return server;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment