10/8/2019 - 4:22 AM

go function get file content type

a function which retruns the content type of the given file by sniffing out some bytes of the file

GetFileContentType returns the content type of given file by sniffing out fist 512 bytes of the file
Use the net/http package's handy DectectContentType function.
Always returns a valid content-type by returning "application/octet-stream" if no others seemed to match.
It also retruns error, if any.
func GetFileContentType(file *os.File) (string, error) {

	// Only the first 512 bytes are used to sniff the content type.
	buffer := make([]byte, 512)
	_, err := file.Read(buffer)
	if err != nil {
		return "", err

	contentType := http.DetectContentType(buffer)
	return contentType, nil