How to detect the content type of a file in Golang?

Go ProgrammingServer Side ProgrammingProgramming

Consider a case where we want to get the content type of a file in Golang for whatever reasons. In order to do that, we must first know how to open the file and read some of its bytes into a buffer slice which we will then pass to a function that will help us in detecting the type of the file.

The first step is to open the file whose type we want to check.

Open the File

Consider that we have a file named sample.pdf whose contentType is what we want to know. In order to open the file, we need to follow the code shown in the code snippet below.

// Open the file whose type you
// want to check
file, err := os.Open("sample.pdf")

if err != nil {
   panic(err)
}

defer file.Close()

In the above snippet, we are opening a file named sample.pdf and then if we encounter any error, we are calling the panic function.

Notice that we are also deferring the Close() method on the file, which is always a good practice.

Read the Data from the File

The next step is to read the data from the file, which we can do with the help of the Read() method that is present in the os package.

The code snippet shown below denotes how we can read the data from the file and then store it in a buffer for later use.

// to sniff the content type only the first
// 512 bytes are used.

buf := make([]byte, 512)

_, err := out.Read(buf)

if err != nil {
   return "", err
}

Detect the Content Type

Now, the final step is to invoke the DetectContentType() function that http package provides us with.

Here is the full program code −

package main

import (
   "fmt"
   "net/http"
   "os"
)

func main() {

   // Open the file whose type you
   // want to check
   file, err := os.Open("sample.pdf")

   if err != nil {
      panic(err)
   }

   defer file.Close()

   // Get the file content
   contentType, err := GetFileContentType(file)

   if err != nil {
      panic(err)
   }

   fmt.Println("Content Type of file is: " + contentType)
}

func GetFileContentType(ouput *os.File) (string, error) {

   // to sniff the content type only the first
   // 512 bytes are used.

   buf := make([]byte, 512)

   _, err := ouput.Read(buf)

   if err != nil {
      return "", err
   }

   // the function that actually does the trick
   contentType := http.DetectContentType(buf)

      return contentType, nil
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

Content Type: application/pdf
raja
Updated on 01-Nov-2021 06:39:05

Advertisements