Merge from mainline (167278:168000).
[official-gcc/graphite-test-results.git] / libgo / go / mime / type.go
bloba10b780ae95c94d0bf68128c7d26daf9d2d46127
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.
5 // The mime package implements parts of the MIME spec.
6 package mime
8 import (
9 "bufio"
10 "os"
11 "strings"
12 "sync"
15 var typeFiles = []string{
16 "/etc/mime.types",
17 "/etc/apache2/mime.types",
18 "/etc/apache/mime.types",
21 var mimeTypes = map[string]string{
22 ".css": "text/css",
23 ".gif": "image/gif",
24 ".htm": "text/html; charset=utf-8",
25 ".html": "text/html; charset=utf-8",
26 ".jpg": "image/jpeg",
27 ".js": "application/x-javascript",
28 ".pdf": "application/pdf",
29 ".png": "image/png",
30 ".xml": "text/xml; charset=utf-8",
33 var mimeLock sync.RWMutex
35 func loadMimeFile(filename string) {
36 f, err := os.Open(filename, os.O_RDONLY, 0666)
37 if err != nil {
38 return
41 reader := bufio.NewReader(f)
42 for {
43 line, err := reader.ReadString('\n')
44 if err != nil {
45 f.Close()
46 return
48 fields := strings.Fields(line)
49 if len(fields) <= 1 || fields[0][0] == '#' {
50 continue
52 typename := fields[0]
53 if strings.HasPrefix(typename, "text/") {
54 typename += "; charset=utf-8"
56 for _, ext := range fields[1:] {
57 if ext[0] == '#' {
58 break
60 mimeTypes["."+ext] = typename
65 func initMime() {
66 for _, filename := range typeFiles {
67 loadMimeFile(filename)
71 var once sync.Once
73 // TypeByExtension returns the MIME type associated with the file extension ext.
74 // The extension ext should begin with a leading dot, as in ".html".
75 // When ext has no associated type, TypeByExtension returns "".
77 // The built-in table is small but is is augmented by the local
78 // system's mime.types file(s) if available under one or more of these
79 // names:
81 // /etc/mime.types
82 // /etc/apache2/mime.types
83 // /etc/apache/mime.types
84 func TypeByExtension(ext string) string {
85 once.Do(initMime)
86 mimeLock.RLock()
87 typename := mimeTypes[ext]
88 mimeLock.RUnlock()
89 return typename
92 // AddExtensionType sets the MIME type associated with
93 // the extension ext to typ. The extension should begin with
94 // a leading dot, as in ".html".
95 func AddExtensionType(ext, typ string) os.Error {
96 once.Do(initMime)
97 if len(ext) < 1 || ext[0] != '.' {
98 return os.EINVAL
100 mimeLock.Lock()
101 mimeTypes[ext] = typ
102 mimeLock.Unlock()
103 return nil