Created
July 4, 2011 21:47
-
-
Save psema4/1063987 to your computer and use it in GitHub Desktop.
A Static Web Server in Node.js with simple Access Control
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
#!/usr/bin/env node | |
var http = require('http'), | |
url = require('url'), | |
fs = require('fs'), | |
util = require('util'), | |
host = '127.0.0.1', | |
port = 8080, | |
useBAC = true, | |
mimeTypes = { | |
html: 'text/html', | |
htm: 'text/html', | |
js: 'text/javascript', | |
css: 'text/css', | |
jpg: 'image/jpeg', | |
jpeg: 'image/jpeg', | |
png: 'image/png', | |
gif: 'image/gif', | |
ico: 'image/x-icon' | |
}, | |
lists = { | |
white: { | |
'127.0.0.1': true | |
}, | |
black: { | |
//'127.0.0.1': true | |
} | |
}; | |
http.createServer(function (req, res) { | |
// Basic Access Control | |
var okToServe = false; | |
if (useBAC) { | |
// Equivalent to "Order Allow,Deny" in Apache | |
if (req.connection.remoteAddress in lists.white) okToServe = true; | |
if (req.connection.remoteAddress in lists.black) okToServe = false; | |
} else { | |
okToServe = true; | |
} | |
if (okToServe) { | |
var parsedUrl = url.parse(req.url), | |
filename = (parsedUrl.pathname == '/') ? '/index.html' : parsedUrl.pathname, | |
extension = filename.match(/[a-zA-Z0-9]+\.(.+)$/)[1].toLowerCase(); | |
fs.readFile('./htdocs' + filename, function(err, data) { | |
if (err) { | |
if (err.code == 'ENOENT') { | |
log(404, req.connection.remoteAddress, err.message); | |
res.writeHead(404, {'Content-Type': 'text/plain'}); | |
res.end('Resource Not Found\n'); | |
} else { | |
log(500, req.connection.remoteAddress, err.message); | |
res.writeHead(500, {'Content-Type': 'text/plain'}); | |
res.end('Internal Server Error\n'); | |
} | |
} else { | |
log(200, req.connection.remoteAddress, filename); | |
res.writeHead(200, {'Content-Type': mimeTypes[extension]}); | |
res.end(data); | |
} | |
}); | |
} else { | |
log(403, req.connection.remoteAddress, 'Access Denied: Forbidden by access control'); | |
res.writeHead(403, {'Content-Type': 'text/plain'}); | |
res.end('Forbidden\n'); | |
} | |
}).listen(port, host); | |
console.log('Server running at http://' + host + ':' + port + '/'); | |
function log(code, remoteAddr, message) { | |
util.log(code + ' ' + remoteAddr + ' ' + message); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment