]> Cypherpunks repositories - gostls13.git/commitdiff
mime: fix ExtensionsByType bug when there are duplicates
authorBrad Fitzpatrick <bradfitz@golang.org>
Tue, 14 Jan 2020 18:15:25 +0000 (18:15 +0000)
committerBrad Fitzpatrick <bradfitz@golang.org>
Tue, 25 Feb 2020 21:09:55 +0000 (21:09 +0000)
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 <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>

src/mime/type.go
src/mime/type_test.go

index aa05077e221220af0ab84f6a5118cbb095991aba..260c535af059d965843ae71ad13de6e35d0ff1ff 100644 (file)
@@ -7,6 +7,7 @@ package mime
 
 import (
        "fmt"
+       "sort"
        "strings"
        "sync"
 )
@@ -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))
@@ -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
index e7aef9a1968b4defe869a6b30ddb5a80a3d5a7f6..f10e6343f9c4592dd6e22979e8f9fb5b8e71f73a 100644 (file)
@@ -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)
+               }
+       }
+}