Navigation Menu

Skip to content

Commit

Permalink
Started ETag support
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Sep 13, 2010
1 parent 4b2b8d1 commit 181c63d
Showing 1 changed file with 32 additions and 6 deletions.
38 changes: 32 additions & 6 deletions lib/connect/middleware/staticProvider.js
Expand Up @@ -85,7 +85,7 @@ module.exports = function staticProvider(options){
res.writeHead(200, hit.headers);
res.end(hit.body);
} else {
notModified(res);
notModified(res, hit.headers);
}
return;
}
Expand All @@ -112,12 +112,13 @@ module.exports = function staticProvider(options){
"Content-Type": utils.mime.type(filename),
"Content-Length": stat.size,
"Last-Modified": stat.mtime.toUTCString(),
"Cache-Control": "public max-age=" + maxAge
"Cache-Control": "public max-age=" + maxAge,
"ETag": etag(stat)
};

// Conditional GET
if (!modified(req, headers)) {
return notModified(res);
return notModified(res, headers);
}

res.writeHead(200, headers);
Expand Down Expand Up @@ -154,7 +155,9 @@ module.exports = function staticProvider(options){

function modified(req, headers) {
var modifiedSince = req.headers['if-modified-since'],
lastModified = headers['Last-Modified'];
lastModified = headers['Last-Modified'],
noneMatch = req.headers['if-none-match'],
etag = headers['ETag'];

// Check If-Modified-Since
if (modifiedSince && lastModified) {
Expand All @@ -165,19 +168,42 @@ function modified(req, headers) {
if (lastModified <= modifiedSince) return false;
}
}

// Check If-None-Match
if (noneMatch && etag && noneMatch == etag) {
return false;
}

return true;
}

/**
* Return an ETag in the form of size-mtime.
*
* @param {Object} stat
* @return {String}
* @api private
*/

function etag(stat) {
return stat.size + '-' + Number(stat.mtime);
}

/**
* Respond with 304 "Not Modified".
*
* @param {ServerResponse} res
* @param {Object} headers
* @api private
*/

function notModified(res) {
res.writeHead(304);
function notModified(res, headers) {
Object.keys(headers).forEach(function(field){
if (0 == field.indexOf('Content')) {
delete headers[field];
}
});
res.writeHead(304, headers);
res.end();
}

Expand Down

0 comments on commit 181c63d

Please sign in to comment.