3 var sys = require('sys'),
4 http = require('http'),
7 events = require('events');
9 var DEFAULT_PORT = 8000;
13 'GET': createServlet(StaticServlet),
14 'HEAD': createServlet(StaticServlet)
15 }).start(Number(argv[2]) || DEFAULT_PORT);
18 function escapeHtml(value) {
19 return value.toString().
22 replace('"', '"');
25 function createServlet(Class) {
26 var servlet = new Class();
27 return servlet.handleRequest.bind(servlet);
31 * An Http server implementation that uses a map of methods to decide
34 * @param {Object} Map of method => Handler function
36 function HttpServer(handlers) {
37 this.handlers = handlers;
38 this.server = http.createServer(this.handleRequest_.bind(this));
41 HttpServer.prototype.start = function(port) {
43 this.server.listen(port);
44 sys.puts('Http Server running at http://localhost:' + port + '/');
47 HttpServer.prototype.parseUrl_ = function(urlString) {
48 var parsed = url.parse(urlString);
49 parsed.pathname = url.resolve('/', parsed.pathname);
50 return url.parse(url.format(parsed), true);
53 HttpServer.prototype.handleRequest_ = function(req, res) {
54 var logEntry = req.method + ' ' + req.url;
55 if (req.headers['user-agent']) {
56 logEntry += ' ' + req.headers['user-agent'];
59 req.url = this.parseUrl_(req.url);
60 var handler = this.handlers[req.method];
65 handler.call(this, req, res);
70 * Handles static content.
72 function StaticServlet() {}
74 StaticServlet.MimeMap = {
78 'xml': 'application/xml',
79 'json': 'application/json',
80 'js': 'application/javascript',
87 StaticServlet.prototype.handleRequest = function(req, res) {
89 var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/, function(match, hex){
90 return String.fromCharCode(parseInt(hex, 16));
92 var parts = path.split('/');
93 if (parts[parts.length-1].charAt(0) === '.')
94 return self.sendForbidden_(req, res, path);
95 fs.stat(path, function(err, stat) {
97 return self.sendMissing_(req, res, path);
98 if (stat.isDirectory())
99 return self.sendDirectory_(req, res, path);
100 return self.sendFile_(req, res, path);
104 StaticServlet.prototype.sendError_ = function(req, res, error) {
106 'Content-Type': 'text/html'
108 res.write('<!doctype html>\n');
109 res.write('<title>Internal Server Error</title>\n');
110 res.write('<h1>Internal Server Error</h1>');
111 res.write('<pre>' + escapeHtml(sys.inspect(error)) + '</pre>');
112 sys.puts('500 Internal Server Error');
113 sys.puts(sys.inspect(error));
116 StaticServlet.prototype.sendMissing_ = function(req, res, path) {
117 path = path.substring(1);
119 'Content-Type': 'text/html'
121 res.write('<!doctype html>\n');
122 res.write('<title>404 Not Found</title>\n');
123 res.write('<h1>Not Found</h1>');
125 '<p>The requested URL ' +
127 ' was not found on this server.</p>'
130 sys.puts('404 Not Found: ' + path);
133 StaticServlet.prototype.sendForbidden_ = function(req, res, path) {
134 path = path.substring(1);
136 'Content-Type': 'text/html'
138 res.write('<!doctype html>\n');
139 res.write('<title>403 Forbidden</title>\n');
140 res.write('<h1>Forbidden</h1>');
142 '<p>You do not have permission to access ' +
143 escapeHtml(path) + ' on this server.</p>'
146 sys.puts('403 Forbidden: ' + path);
149 StaticServlet.prototype.sendRedirect_ = function(req, res, redirectUrl) {
151 'Content-Type': 'text/html',
152 'Location': redirectUrl
154 res.write('<!doctype html>\n');
155 res.write('<title>301 Moved Permanently</title>\n');
156 res.write('<h1>Moved Permanently</h1>');
158 '<p>The document has moved <a href="' +
163 sys.puts('401 Moved Permanently: ' + redirectUrl);
166 StaticServlet.prototype.sendFile_ = function(req, res, path) {
168 var file = fs.createReadStream(path);
170 'Content-Type': StaticServlet.
171 MimeMap[path.split('.').pop()] || 'text/plain'
173 if (req.method === 'HEAD') {
176 file.on('data', res.write.bind(res));
177 file.on('close', function() {
180 file.on('error', function(error) {
181 self.sendError_(req, res, error);
186 StaticServlet.prototype.sendDirectory_ = function(req, res, path) {
188 if (path.match(/[^\/]$/)) {
189 req.url.pathname += '/';
190 var redirectUrl = url.format(url.parse(url.format(req.url)));
191 return self.sendRedirect_(req, res, redirectUrl);
193 fs.readdir(path, function(err, files) {
195 return self.sendError_(req, res, error);
198 return self.writeDirectoryIndex_(req, res, path, []);
200 var remaining = files.length;
201 files.forEach(function(fileName, index) {
202 fs.stat(path + '/' + fileName, function(err, stat) {
204 return self.sendError_(req, res, err);
205 if (stat.isDirectory()) {
206 files[index] = fileName + '/';
209 return self.writeDirectoryIndex_(req, res, path, files);
215 StaticServlet.prototype.writeDirectoryIndex_ = function(req, res, path, files) {
216 path = path.substring(1);
218 'Content-Type': 'text/html'
220 if (req.method === 'HEAD') {
224 res.write('<!doctype html>\n');
225 res.write('<title>' + escapeHtml(path) + '</title>\n');
226 res.write('<style>\n');
227 res.write(' ol { list-style-type: none; font-size: 1.2em; }\n');
228 res.write('</style>\n');
229 res.write('<h1>Directory: ' + escapeHtml(path) + '</h1>');
231 files.forEach(function(fileName) {
232 if (fileName.charAt(0) !== '.') {
233 res.write('<li><a href="' +
234 escapeHtml(fileName) + '">' +
235 escapeHtml(fileName) + '</a></li>');