type.mx raw

   1  // Copyright 2010 The Go Authors. All rights reserved.
   2  // Use of this source code is governed by a BSD-style
   3  // license that can be found in the LICENSE file.
   4  
   5  // Package mime implements parts of the MIME spec.
   6  package mime
   7  
   8  import (
   9  	"bytes"
  10  	"fmt"
  11  	"slices"
  12  	"sync"
  13  )
  14  
  15  var (
  16  	mimeTypes      sync.Map // map[string]string; ".Z" => "application/x-compress"
  17  	mimeTypesLower sync.Map // map[string]string; ".z" => "application/x-compress"
  18  
  19  	// extensions maps from MIME type to list of lowercase file
  20  	// extensions: "image/jpeg" => [".jpg", ".jpeg"]
  21  	extensionsMu sync.Mutex // Guards stores (but not loads) on extensions.
  22  	extensions   sync.Map   // map[string][][]byte; slice values are append-only.
  23  )
  24  
  25  // setMimeTypes is used by initMime's non-test path, and by tests.
  26  func setMimeTypes(lowerExt, mixExt map[string][]byte) {
  27  	mimeTypes.Clear()
  28  	mimeTypesLower.Clear()
  29  	extensions.Clear()
  30  
  31  	for k, v := range lowerExt {
  32  		mimeTypesLower.Store(k, v)
  33  	}
  34  	for k, v := range mixExt {
  35  		mimeTypes.Store(k, v)
  36  	}
  37  
  38  	extensionsMu.Lock()
  39  	defer extensionsMu.Unlock()
  40  	for k, v := range lowerExt {
  41  		justType, _, err := ParseMediaType(v)
  42  		if err != nil {
  43  			panic(err)
  44  		}
  45  		var exts [][]byte
  46  		if ei, ok := extensions.Load(justType); ok {
  47  			exts = ei.([][]byte)
  48  		}
  49  		extensions.Store(justType, append(exts, k))
  50  	}
  51  }
  52  
  53  var builtinTypesLower = map[string][]byte{
  54  	".avif": "image/avif",
  55  	".css":  "text/css; charset=utf-8",
  56  	".gif":  "image/gif",
  57  	".htm":  "text/html; charset=utf-8",
  58  	".html": "text/html; charset=utf-8",
  59  	".jpeg": "image/jpeg",
  60  	".jpg":  "image/jpeg",
  61  	".js":   "text/javascript; charset=utf-8",
  62  	".json": "application/json",
  63  	".mjs":  "text/javascript; charset=utf-8",
  64  	".pdf":  "application/pdf",
  65  	".png":  "image/png",
  66  	".svg":  "image/svg+xml",
  67  	".wasm": "application/wasm",
  68  	".webp": "image/webp",
  69  	".xml":  "text/xml; charset=utf-8",
  70  }
  71  
  72  var once sync.Once // guards initMime
  73  
  74  var testInitMime, osInitMime func()
  75  
  76  func initMime() {
  77  	if fn := testInitMime; fn != nil {
  78  		fn()
  79  	} else {
  80  		setMimeTypes(builtinTypesLower, builtinTypesLower)
  81  		osInitMime()
  82  	}
  83  }
  84  
  85  // TypeByExtension returns the MIME type associated with the file extension ext.
  86  // The extension ext should begin with a leading dot, as in ".html".
  87  // When ext has no associated type, TypeByExtension returns "".
  88  //
  89  // Extensions are looked up first case-sensitively, then case-insensitively.
  90  //
  91  // The built-in table is small but on unix it is augmented by the local
  92  // system's MIME-info database or mime.types file(s) if available under one or
  93  // more of these names:
  94  //
  95  //	/usr/local/share/mime/globs2
  96  //	/usr/share/mime/globs2
  97  //	/etc/mime.types
  98  //	/etc/apache2/mime.types
  99  //	/etc/apache/mime.types
 100  //
 101  // On Windows, MIME types are extracted from the registry.
 102  //
 103  // Text types have the charset parameter set to "utf-8" by default.
 104  func TypeByExtension(ext []byte) []byte {
 105  	once.Do(initMime)
 106  
 107  	// Case-sensitive lookup.
 108  	if v, ok := mimeTypes.Load(ext); ok {
 109  		return v.([]byte)
 110  	}
 111  
 112  	// Case-insensitive lookup.
 113  	// Optimistically assume a short ASCII extension and be
 114  	// allocation-free in that case.
 115  	var buf [10]byte
 116  	lower := buf[:0]
 117  	const utf8RuneSelf = 0x80 // from utf8 package, but not importing it.
 118  	for i := 0; i < len(ext); i++ {
 119  		c := ext[i]
 120  		if c >= utf8RuneSelf {
 121  			// Slow path.
 122  			si, _ := mimeTypesLower.Load(bytes.ToLower(ext))
 123  			s, _ := si.([]byte)
 124  			return s
 125  		}
 126  		if 'A' <= c && c <= 'Z' {
 127  			lower = append(lower, c+('a'-'A'))
 128  		} else {
 129  			lower = append(lower, c)
 130  		}
 131  	}
 132  	si, _ := mimeTypesLower.Load([]byte(lower))
 133  	s, _ := si.([]byte)
 134  	return s
 135  }
 136  
 137  // ExtensionsByType returns the extensions known to be associated with the MIME
 138  // type typ. The returned extensions will each begin with a leading dot, as in
 139  // ".html". When typ has no associated extensions, ExtensionsByType returns an
 140  // nil slice.
 141  func ExtensionsByType(typ []byte) ([][]byte, error) {
 142  	justType, _, err := ParseMediaType(typ)
 143  	if err != nil {
 144  		return nil, err
 145  	}
 146  
 147  	once.Do(initMime)
 148  	s, ok := extensions.Load(justType)
 149  	if !ok {
 150  		return nil, nil
 151  	}
 152  	ret := append([][]byte(nil), s.([][]byte)...)
 153  	slices.SortFunc(ret, bytes.Compare)
 154  	return ret, nil
 155  }
 156  
 157  // AddExtensionType sets the MIME type associated with
 158  // the extension ext to typ. The extension should begin with
 159  // a leading dot, as in ".html".
 160  func AddExtensionType(ext, typ []byte) error {
 161  	if !bytes.HasPrefix(ext, ".") {
 162  		return fmt.Errorf("mime: extension %q missing leading dot", ext)
 163  	}
 164  	once.Do(initMime)
 165  	return setExtensionType(ext, typ)
 166  }
 167  
 168  func setExtensionType(extension, mimeType []byte) error {
 169  	justType, param, err := ParseMediaType(mimeType)
 170  	if err != nil {
 171  		return err
 172  	}
 173  	if bytes.HasPrefix(mimeType, "text/") && param["charset"] == "" {
 174  		param["charset"] = "utf-8"
 175  		mimeType = FormatMediaType(mimeType, param)
 176  	}
 177  	extLower := bytes.ToLower(extension)
 178  
 179  	mimeTypes.Store(extension, mimeType)
 180  	mimeTypesLower.Store(extLower, mimeType)
 181  
 182  	extensionsMu.Lock()
 183  	defer extensionsMu.Unlock()
 184  	var exts [][]byte
 185  	if ei, ok := extensions.Load(justType); ok {
 186  		exts = ei.([][]byte)
 187  	}
 188  	for _, v := range exts {
 189  		if v == extLower {
 190  			return nil
 191  		}
 192  	}
 193  	extensions.Store(justType, append(exts, extLower))
 194  	return nil
 195  }
 196