on error just returns "" does not return "application/octet-stream" as this is considered a detection failure can pass an existing fileInfo to avoid re-statting the file falls back to text/plain for 0 byte files
(path string, fileInfo fs.FileInfo, extended bool)
| 99 | // can pass an existing fileInfo to avoid re-statting the file |
| 100 | // falls back to text/plain for 0 byte files |
| 101 | func DetectMimeType(path string, fileInfo fs.FileInfo, extended bool) string { |
| 102 | if fileInfo == nil { |
| 103 | statRtn, err := os.Stat(path) |
| 104 | if err != nil { |
| 105 | return "" |
| 106 | } |
| 107 | fileInfo = statRtn |
| 108 | } |
| 109 | |
| 110 | if fileInfo.IsDir() || WinSymlinkDir(path, fileInfo.Mode()) { |
| 111 | return "directory" |
| 112 | } |
| 113 | if fileInfo.Mode()&os.ModeNamedPipe == os.ModeNamedPipe { |
| 114 | return "pipe" |
| 115 | } |
| 116 | charDevice := os.ModeDevice | os.ModeCharDevice |
| 117 | if fileInfo.Mode()&charDevice == charDevice { |
| 118 | return "character-special" |
| 119 | } |
| 120 | if fileInfo.Mode()&os.ModeDevice == os.ModeDevice { |
| 121 | return "block-special" |
| 122 | } |
| 123 | ext := strings.ToLower(filepath.Ext(path)) |
| 124 | if mimeType, ok := StaticMimeTypeMap[ext]; ok { |
| 125 | return mimeType |
| 126 | } |
| 127 | if mimeType := mime.TypeByExtension(ext); mimeType != "" { |
| 128 | return mimeType |
| 129 | } |
| 130 | if fileInfo.Size() == 0 { |
| 131 | return "text/plain" |
| 132 | } |
| 133 | if !extended { |
| 134 | return "" |
| 135 | } |
| 136 | fd, err := os.Open(path) |
| 137 | if err != nil { |
| 138 | return "" |
| 139 | } |
| 140 | defer fd.Close() |
| 141 | buf := make([]byte, 512) |
| 142 | // ignore the error (EOF / UnexpectedEOF is fine, just process how much we got back) |
| 143 | n, _ := io.ReadAtLeast(fd, buf, 512) |
| 144 | if n == 0 { |
| 145 | return "" |
| 146 | } |
| 147 | buf = buf[:n] |
| 148 | rtn := http.DetectContentType(buf) |
| 149 | if rtn == "application/octet-stream" { |
| 150 | return "" |
| 151 | } |
| 152 | return rtn |
| 153 | } |
| 154 | |
| 155 | func DetectMimeTypeWithDirEnt(path string, dirEnt fs.DirEntry) string { |
| 156 | if dirEnt != nil { |