Skip to content

Commit

Permalink
Use digest() method in body if available, and only set ETag header if…
Browse files Browse the repository at this point in the history
… truthy.
  • Loading branch information
hns committed May 24, 2011
1 parent 1144f34 commit 15e645c
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions lib/stick/middleware/etag.js
Expand Up @@ -34,27 +34,33 @@ exports.middleware = function etag(next, app) {
var {status, headers, body} = res;

if (status === 200) {
var etags;
var etags, etag;
var header = request.headers["if-none-match"];
if (header) {
etags = header.split(",").map(function(s) s.trim());
}

// we can't rely on body having map(), so we fake it with forEach()
var binBody = [];
body.forEach(function(part) {
binBody.push(part.toByteString());
});
var etag = '"' + digest(binBody) + '"';
headers = Headers(headers);
headers.set("ETag", etag);
// if body provides a digest() method use that
if (typeof body.digest === "function") {
etag = body.digest();
} else {
// we can't rely on body having map(), so we fake it with forEach()
var binBody = [];
body.forEach(function(part) {
binBody.push(part.toByteString());
});
etag = digest(binBody);
}
if (etag) {
headers = Headers(headers);
headers.set("ETag", '"' + etag + '"');
}

if (etags && strings.contains(etags, etag)) {
// return not-modified response
headers.unset('Content-Length');
return {status: 304, headers: headers, body: []};
}

// body has been converted to ByteStrings as a byproduct of digest()
res.body = binBody;
}
Expand Down

0 comments on commit 15e645c

Please sign in to comment.