| 1 | // Package mimetype uses magic number signatures to detect the MIME type of a file. |
| 2 | // |
| 3 | // File formats are stored in a hierarchy with "application/octet-stream" at its root. |
| 4 | // For example, the hierarchy for HTML format is application/octet-stream -> |
| 5 | // text/plain -> text/html. |
| 6 | package mimetype |
| 7 | |
| 8 | import ( |
| 9 | "io" |
| 10 | "mime" |
| 11 | "os" |
| 12 | "sync/atomic" |
| 13 | ) |
| 14 | |
| 15 | const defaultLimit uint32 = 4096 |
| 16 | |
| 17 | // readLimit is the maximum number of bytes from the input used when detecting. |
| 18 | var readLimit uint32 = defaultLimit |
| 19 | |
| 20 | // Detect returns the MIME type found from the provided byte slice. |
| 21 | // |
| 22 | // The result is always a valid MIME type, with "application/octet-stream" |
| 23 | // returned when identification failed. |
| 24 | func Detect(in []byte) *MIME { |
| 25 | // Using atomic because readLimit can be written at the same time in other goroutine. |
| 26 | l := atomic.LoadUint32(&readLimit) |
| 27 | if l > 0 && len(in) > int(l) { |
| 28 | in = in[:l] |
| 29 | } |
| 30 | mu.RLock() |
| 31 | defer mu.RUnlock() |
| 32 | return root.match(in, l) |
| 33 | } |
| 34 | |
| 35 | // DetectReader returns the MIME type of the provided reader. |
| 36 | // |
| 37 | // The result is always a valid MIME type, with "application/octet-stream" |
| 38 | // returned when identification failed with or without an error. |
| 39 | // Any error returned is related to the reading from the input reader. |
| 40 | // |
| 41 | // DetectReader assumes the reader offset is at the start. If the input is an |
| 42 | // io.ReadSeeker you previously read from, it should be rewinded before detection: |
| 43 | // |
| 44 | // reader.Seek(0, io.SeekStart) |
| 45 | func DetectReader(r io.Reader) (*MIME, error) { |
| 46 | var in []byte |
| 47 | var err error |
| 48 | |
| 49 | // Using atomic because readLimit can be written at the same time in other goroutine. |
| 50 | l := atomic.LoadUint32(&readLimit) |
| 51 | if l == 0 { |
| 52 | in, err = io.ReadAll(r) |
| 53 | if err != nil { |
| 54 | return errMIME, err |
| 55 | } |
| 56 | } else { |
| 57 | var n int |
| 58 | in = make([]byte, l) |
| 59 | // io.UnexpectedEOF means len(r) < len(in). It is not an error in this case, |
| 60 | // it just means the input file is smaller than the allocated bytes slice. |
| 61 | n, err = io.ReadFull(r, in) |
| 62 | if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { |
| 63 | return errMIME, err |
| 64 | } |
| 65 | in = in[:n] |
| 66 | } |
| 67 | |
| 68 | mu.RLock() |
| 69 | defer mu.RUnlock() |
| 70 | return root.match(in, l), nil |
| 71 | } |
| 72 | |
| 73 | // DetectFile returns the MIME type of the provided file. |
| 74 | // |
| 75 | // The result is always a valid MIME type, with "application/octet-stream" |
| 76 | // returned when identification failed with or without an error. |
| 77 | // Any error returned is related to the opening and reading from the input file. |
| 78 | func DetectFile(path string) (*MIME, error) { |
| 79 | f, err := os.Open(path) |
| 80 | if err != nil { |
| 81 | return errMIME, err |
| 82 | } |
| 83 | defer f.Close() |
| 84 | |
| 85 | return DetectReader(f) |
| 86 | } |
| 87 | |
| 88 | // EqualsAny reports whether s MIME type is equal to any MIME type in mimes. |
| 89 | // MIME type equality test is done on the "type/subtype" section, ignores |
| 90 | // any optional MIME parameters, ignores any leading and trailing whitespace, |
| 91 | // and is case insensitive. |
| 92 | func EqualsAny(s string, mimes ...string) bool { |
| 93 | s, _, _ = mime.ParseMediaType(s) |
| 94 | for _, m := range mimes { |
| 95 | m, _, _ = mime.ParseMediaType(m) |
| 96 | if s == m { |
| 97 | return true |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | return false |
| 102 | } |
| 103 | |
| 104 | // SetLimit sets the maximum number of bytes read from input when detecting the MIME type. |
| 105 | // Increasing the limit provides better detection for file formats which store |
| 106 | // their magical numbers towards the end of the file: docx, pptx, xlsx, etc. |
| 107 | // During detection data is read in a single block of size limit, i.e. it is not buffered. |
| 108 | // A limit of 0 means the whole input file will be used. |
| 109 | func SetLimit(limit uint32) { |
| 110 | // Using atomic because readLimit can be read at the same time in other goroutine. |
| 111 | atomic.StoreUint32(&readLimit, limit) |
| 112 | } |
| 113 | |
| 114 | // Extend adds detection for other file formats. |
| 115 | // It is equivalent to calling [MIME.Extend] on the root MIME type "application/octet-stream". |
| 116 | func Extend(detector func(raw []byte, limit uint32) bool, mime, extension string, aliases ...string) { |
| 117 | root.Extend(detector, mime, extension, aliases...) |
| 118 | } |
| 119 | |
| 120 | // Lookup finds a MIME object by its string representation. |
| 121 | // The representation can be the main MIME type, or any of its aliases. |
| 122 | func Lookup(m string) *MIME { |
| 123 | // We store the MIME types without optional params, so |
| 124 | // perform parsing to extract the target MIME type without optional params. |
| 125 | m, _, _ = mime.ParseMediaType(m) |
| 126 | mu.RLock() |
| 127 | defer mu.RUnlock() |
| 128 | return root.lookup(m) |
| 129 | } |