Skip to content

Commit f0ee49b

Browse files
committed
mime: fix ExtensionsByType bug when there are duplicates
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]>
1 parent 46f9aea commit f0ee49b

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/mime/type.go

+5-2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package mime
77

88
import (
99
"fmt"
10+
"sort"
1011
"strings"
1112
"sync"
1213
)
@@ -49,7 +50,7 @@ func setMimeTypes(lowerExt, mixExt map[string]string) {
4950
panic(err)
5051
}
5152
var exts []string
52-
if ei, ok := extensions.Load(k); ok {
53+
if ei, ok := extensions.Load(justType); ok {
5354
exts = ei.([]string)
5455
}
5556
extensions.Store(justType, append(exts, k))
@@ -151,7 +152,9 @@ func ExtensionsByType(typ string) ([]string, error) {
151152
if !ok {
152153
return nil, nil
153154
}
154-
return append([]string{}, s.([]string)...), nil
155+
ret := append([]string(nil), s.([]string)...)
156+
sort.Strings(ret)
157+
return ret, nil
155158
}
156159

157160
// AddExtensionType sets the MIME type associated with

src/mime/type_test.go

+27
Original file line numberDiff line numberDiff line change
@@ -188,3 +188,30 @@ func BenchmarkExtensionsByType(b *testing.B) {
188188
})
189189
}
190190
}
191+
192+
func TestExtensionsByType2(t *testing.T) {
193+
cleanup := setMimeInit(func() {
194+
clearMimeTypes()
195+
// Initialize built-in types like in type.go before osInitMime.
196+
setMimeTypes(builtinTypesLower, builtinTypesLower)
197+
})
198+
defer cleanup()
199+
200+
tests := []struct {
201+
typ string
202+
want []string
203+
}{
204+
{typ: "image/jpeg", want: []string{".jpeg", ".jpg"}},
205+
}
206+
207+
for _, tt := range tests {
208+
got, err := ExtensionsByType(tt.typ)
209+
if err != nil {
210+
t.Errorf("ExtensionsByType(%q): %v", tt.typ, err)
211+
continue
212+
}
213+
if !reflect.DeepEqual(got, tt.want) {
214+
t.Errorf("ExtensionsByType(%q) = %q; want %q", tt.typ, got, tt.want)
215+
}
216+
}
217+
}

0 commit comments

Comments
 (0)