I'm currently available for contract work & technical writing opportunities. Hire me

How to detect the Content Type of a file in Go

It’s often necessary to detect the content type a file usually for the purpose of determining if an operation is permitted on the file. The Go standard library provides an easy way to check the MIME type of a file through its net/http package.

This package exposes a DetectContentType() method which reads the first 512 bytes of a file and returns a MIME type such as image/png. If it cannot detect the content type of the file, application/octet-stream is returned instead.

resp, err := client.Get("https://freshman.tech/images/dp-illustration.png")
if err != nil {
	log.Fatal(err)
}

defer resp.Body.Close()

// Read the response body as a byte slice
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
	log.Fatal(err)
}

mimeType := http.DetectContentType(bytes)
fmt.Println(mimeType) // image/png

The DetectContentType() method supports only a limited number of file types so if you need something more robust than what it offers, consider using the mimetype library which supports a much greater range of file types.

Thanks for reading, and happy coding!