From fc85699a9506c6f6376742ea92a9a549af2eba84 Mon Sep 17 00:00:00 2001 From: Larry Lv Date: Sun, 26 Jul 2020 17:48:24 -0700 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20Refactor=20etag=20stale=20checki?= =?UTF-8?q?ng?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ctx.go | 10 +--------- utils.go | 25 ++++++++++++++++--------- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/ctx.go b/ctx.go index 07912ba5..6aa93fb0 100644 --- a/ctx.go +++ b/ctx.go @@ -449,15 +449,7 @@ func (ctx *Ctx) Fresh() bool { if etag == "" { return false } - var etagStale = true - var matches = parseTokenList(getBytes(noneMatch)) - for _, match := range matches { - if match == etag || match == "W/"+etag || "W/"+match == etag { - etagStale = false - break - } - } - if etagStale { + if isEtagStale(etag, getBytes(noneMatch)) { return false } diff --git a/utils.go b/utils.go index 121885d1..06bc0940 100644 --- a/utils.go +++ b/utils.go @@ -163,14 +163,14 @@ func getOffer(header string, offers ...string) string { return "" } -// Adapted from: -// https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L110 -func parseTokenList(noneMatchBytes []byte) []string { +func isEtagStale(etag string, noneMatchBytes []byte) bool { var ( - start int - end int - list []string + start int + end int + matches []string ) + // Adapted from: + // https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L110 for i := range noneMatchBytes { switch noneMatchBytes[i] { case 0x20: @@ -179,7 +179,7 @@ func parseTokenList(noneMatchBytes []byte) []string { end = i + 1 } case 0x2c: - list = append(list, getString(noneMatchBytes[start:end])) + matches = append(matches, getString(noneMatchBytes[start:end])) start = i + 1 end = i + 1 default: @@ -187,8 +187,15 @@ func parseTokenList(noneMatchBytes []byte) []string { } } - list = append(list, getString(noneMatchBytes[start:end])) - return list + matches = append(matches, getString(noneMatchBytes[start:end])) + + for _, match := range matches { + if match == etag || match == "W/"+etag || "W/"+match == etag { + return false + } + } + + return true } func isIPv6(address string) bool {