1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-21 23:33:18 +00:00

Merge pull request #678 from larrylv/larrylv/improve_etag_stale_checking

🧹 Refactor etag stale checking
This commit is contained in:
fenny 2020-07-27 04:39:10 +02:00 committed by GitHub
commit aafd222eaf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 20 deletions

10
ctx.go
View File

@ -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
}

View File

@ -632,6 +632,23 @@ func Test_Ctx_FormValue(t *testing.T) {
utils.AssertEqual(t, StatusOK, resp.StatusCode, "Status code")
}
// go test -v -run=^$ -bench=Benchmark_Ctx_Fresh_StaleEtag -benchmem -count=4
func Benchmark_Ctx_Fresh_StaleEtag(b *testing.B) {
app := New()
ctx := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(ctx)
for n := 0; n < b.N; n++ {
ctx.Fasthttp.Request.Header.Set(HeaderIfNoneMatch, "a, b, c, d")
ctx.Fasthttp.Request.Header.Set(HeaderCacheControl, "c")
ctx.Fresh()
ctx.Fasthttp.Request.Header.Set(HeaderIfNoneMatch, "a, b, c, d")
ctx.Fasthttp.Request.Header.Set(HeaderCacheControl, "e")
ctx.Fresh()
}
}
// go test -run Test_Ctx_Fresh
func Test_Ctx_Fresh(t *testing.T) {
t.Parallel()

View File

@ -163,14 +163,19 @@ 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 {
var (
start int
end int
list []string
)
func matchEtag(s string, etag string) bool {
if s == etag || s == "W/"+etag || "W/"+s == etag {
return true
}
return false
}
func isEtagStale(etag string, noneMatchBytes []byte) bool {
var start, end int
// Adapted from:
// https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L110
for i := range noneMatchBytes {
switch noneMatchBytes[i] {
case 0x20:
@ -179,7 +184,9 @@ func parseTokenList(noneMatchBytes []byte) []string {
end = i + 1
}
case 0x2c:
list = append(list, getString(noneMatchBytes[start:end]))
if matchEtag(getString(noneMatchBytes[start:end]), etag) {
return false
}
start = i + 1
end = i + 1
default:
@ -187,8 +194,7 @@ func parseTokenList(noneMatchBytes []byte) []string {
}
}
list = append(list, getString(noneMatchBytes[start:end]))
return list
return !matchEtag(getString(noneMatchBytes[start:end]), etag)
}
func isIPv6(address string) bool {