...
Run Format

Source file src/mime/type.go

Documentation: mime

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

View as plain text