Golang Code

How Detect Content Type of a File

· 0 word · 0 minutes read #content-type #sniff #mime #file #detect #read

We can use the net/http package to find the content type, or mime type, of a file. To do this, we open the file and read the first 512 bytes (as the DetectContentType() function only uses the first 512 bytes, there’s no point in doing more than needed). This function will then return a mime type, like application/json or image/jpg for instance.

package main

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

func main() {

    // Open File
    f, err := os.Open("test.pdf")
    if err != nil {
        panic(err)
    }
    defer f.Close()

    // Get the content
    contentType, err := GetFileContentType(f)
    if err != nil {
        panic(err)
    }

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

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

    // Only the first 512 bytes are used to sniff the content type.
    buffer := make([]byte, 512)

    _, err := out.Read(buffer)
    if err != nil {
        return "", err
    }

    // 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.
    contentType := http.DetectContentType(buffer)

    return contentType, nil
}
Image of Author Edd Turtle

Author: Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below. Thanks for reading!