To determine the MIME type of a file in Go, you can use the net/http
package's DetectContentType
function. Here's an example:
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
file, err := os.Open("example.jpg")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
// Read the first 512 bytes to determine the file's MIME type
buffer := make([]byte, 512)
_, err = file.Read(buffer)
if err != nil {
fmt.Println("Error reading file:", err)
return
}
// Get the file's MIME type
mimeType := http.DetectContentType(buffer)
fmt.Println("MIME type:", mimeType)
}
In this example, we open the file example.jpg
, read the first 512 bytes, and then pass that buffer to the DetectContentType
function. The function returns the MIME type of the file, which we then print to the console.
Note that DetectContentType
uses a byte pattern matching algorithm, so it relies on the contents of the file rather than the file extension, which makes it more reliable for determining the MIME type.