From 103c9496ad8f7e687b8291b56750190012091a96 Mon Sep 17 00:00:00 2001 From: Ernest Micklei Date: Sun, 12 May 2019 10:45:41 +0200 Subject: [PATCH] fix issue #400, mime parse error --- mime.go | 11 ++++++++--- mime_test.go | 8 ++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/mime.go b/mime.go index d7ea2b61..33014471 100644 --- a/mime.go +++ b/mime.go @@ -22,7 +22,10 @@ func insertMime(l []mime, e mime) []mime { return append(l, e) } +const qFactorWeightingKey = "q" + // sortedMimes returns a list of mime sorted (desc) by its specified quality. +// e.g. text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 func sortedMimes(accept string) (sorted []mime) { for _, each := range strings.Split(accept, ",") { typeAndQuality := strings.Split(strings.Trim(each, " "), ";") @@ -30,14 +33,16 @@ func sortedMimes(accept string) (sorted []mime) { sorted = insertMime(sorted, mime{typeAndQuality[0], 1.0}) } else { // take factor - parts := strings.Split(typeAndQuality[1], "=") - if len(parts) == 2 { - f, err := strconv.ParseFloat(parts[1], 64) + qAndWeight := strings.Split(typeAndQuality[1], "=") + if len(qAndWeight) == 2 && strings.Trim(qAndWeight[0], " ") == qFactorWeightingKey { + f, err := strconv.ParseFloat(qAndWeight[1], 64) if err != nil { traceLogger.Printf("unable to parse quality in %s, %v", each, err) } else { sorted = insertMime(sorted, mime{typeAndQuality[0], f}) } + } else { + sorted = insertMime(sorted, mime{typeAndQuality[0], 1.0}) } } } diff --git a/mime_test.go b/mime_test.go index a910bb10..e4177845 100644 --- a/mime_test.go +++ b/mime_test.go @@ -15,3 +15,11 @@ func TestSortMimes(t *testing.T) { t.Errorf("bad sort order of mime types:%s", got) } } + +func TestNonNumberQualityInAccept_issue400(t *testing.T) { + accept := `text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3` + result := sortedMimes(accept) + if got, want := len(result), 7; got != want { + t.Errorf("got %d want %d quality mimes", got, want) + } +}