detectContentType detects the content type of a file by mime or extension
(f http.File, fi fs.FileInfo)
| 119 | |
| 120 | // detectContentType detects the content type of a file by mime or extension |
| 121 | func detectContentType(f http.File, fi fs.FileInfo) string { |
| 122 | var ( |
| 123 | tmp [512]byte |
| 124 | mimetype string |
| 125 | ) |
| 126 | |
| 127 | if n, err := io.ReadFull(f, tmp[:]); err == nil || err == io.ErrUnexpectedEOF { |
| 128 | mimetype = http.DetectContentType(tmp[:n]) |
| 129 | } |
| 130 | |
| 131 | f.Seek(0, io.SeekStart) // rewind file position |
| 132 | |
| 133 | if len(mimetype) == 0 || |
| 134 | strings.HasPrefix(mimetype, "text/plain") || |
| 135 | strings.HasPrefix(mimetype, "application/octet-stream") { |
| 136 | if m := mime.TypeByExtension(filepath.Ext(fi.Name())); len(m) > 0 { |
| 137 | mimetype = m |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | return mimetype |
| 142 | } |