Skip to content

Commit

Permalink
mime: fix ExtensionsByType bug when there are duplicates
Browse files Browse the repository at this point in the history
Also, sort them so the results aren't random.

Thanks to @junedev for the bug report & repro.

Fixes #36524

Change-Id: Ic9197ebeceddfb3d0aee895d8fc12ce4d205b164
Reviewed-on: https://go-review.googlesource.com/c/go/+/214680
Reviewed-by: Ian Lance Taylor <[email protected]>
Run-TryBot: Ian Lance Taylor <[email protected]>
TryBot-Result: Gobot Gobot <[email protected]>
  • Loading branch information
bradfitz committed Feb 25, 2020
1 parent 46f9aea commit f0ee49b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/mime/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package mime

import (
"fmt"
"sort"
"strings"
"sync"
)
Expand Down Expand Up @@ -49,7 +50,7 @@ func setMimeTypes(lowerExt, mixExt map[string]string) {
panic(err)
}
var exts []string
if ei, ok := extensions.Load(k); ok {
if ei, ok := extensions.Load(justType); ok {
exts = ei.([]string)
}
extensions.Store(justType, append(exts, k))
Expand Down Expand Up @@ -151,7 +152,9 @@ func ExtensionsByType(typ string) ([]string, error) {
if !ok {
return nil, nil
}
return append([]string{}, s.([]string)...), nil
ret := append([]string(nil), s.([]string)...)
sort.Strings(ret)
return ret, nil
}

// AddExtensionType sets the MIME type associated with
Expand Down
27 changes: 27 additions & 0 deletions src/mime/type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,3 +188,30 @@ func BenchmarkExtensionsByType(b *testing.B) {
})
}
}

func TestExtensionsByType2(t *testing.T) {
cleanup := setMimeInit(func() {
clearMimeTypes()
// Initialize built-in types like in type.go before osInitMime.
setMimeTypes(builtinTypesLower, builtinTypesLower)
})
defer cleanup()

tests := []struct {
typ string
want []string
}{
{typ: "image/jpeg", want: []string{".jpeg", ".jpg"}},
}

for _, tt := range tests {
got, err := ExtensionsByType(tt.typ)
if err != nil {
t.Errorf("ExtensionsByType(%q): %v", tt.typ, err)
continue
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("ExtensionsByType(%q) = %q; want %q", tt.typ, got, tt.want)
}
}
}

0 comments on commit f0ee49b

Please sign in to comment.