Skip to content

Instantly share code, notes, and snippets.

@stonecobra
Created March 8, 2011 22:38
Show Gist options
  • Save stonecobra/861260 to your computer and use it in GitHub Desktop.
Save stonecobra/861260 to your computer and use it in GitHub Desktop.
node.js serving the same content on http and https
//our 'imports', for you java fans out there
var connect = require('connect')
,fs = require('fs')
,http = require('http')
,https = require('https');
//the certs that need to be given to the ssl side, ca is optional
var ssl_options = {
ca: fs.readFileSync(__dirname + '/lib/certs/ssl.ca')
,key: fs.readFileSync(__dirname + '/lib/certs/ssl.key')
,cert: fs.readFileSync(__dirname + '/lib/certs/ssl.cert')
};
//create a standard http server, serving static files
var server = connect.createServer(
connect.logger()
//just create a 'www' directory containing an index.html for the default to work
,connect.static(__dirname + '/www') //staticProvider for older versions of connect
).listen(80);
//send and receive the same info, just on SSL
var ssl = https.createServer(ssl_options, function(request, response) {
var proxy = http.createClient(80, request.headers['host']);
var proxy_request = proxy.request(request.method, request.url, request.headers);
proxy_request.addListener('response', function (proxy_response) {
proxy_response.addListener('data', function(chunk) {
response.write(chunk, 'binary');
});
proxy_response.addListener('end', function() {
response.end();
});
response.writeHead(proxy_response.statusCode, proxy_response.headers);
});
request.addListener('data', function(chunk) {
proxy_request.write(chunk, 'binary');
});
request.addListener('end', function() {
proxy_request.end();
});
}).listen(443);
@SanzSeraph
Copy link

Couldn't you simply define the callback function separately and than initialize an http.Server instance and an https.Server instance that both make use of the same request handling callback?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment