Skip to content

Commit

Permalink
fix issue #400, mime parse error
Browse files Browse the repository at this point in the history
  • Loading branch information
emicklei committed May 12, 2019
1 parent d2b8501 commit 103c949
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
11 changes: 8 additions & 3 deletions mime.go
Expand Up @@ -22,22 +22,27 @@ 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, " "), ";")
if len(typeAndQuality) == 1 {
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})
}
}
}
Expand Down
8 changes: 8 additions & 0 deletions mime_test.go
Expand Up @@ -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)
}
}

0 comments on commit 103c949

Please sign in to comment.