Golang : Find out mime type from bytes in buffer
Problem :
You are building an application that need to detect the MIME type of an object. Such as an email application that handles file attachment. How to find out the MIME type of an object or file ?
Solution :
Use net/http.DetectContentType()
function to detect the file or object MIME type. For example :
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
filename := os.Args[1]
if len(os.Args) != 2 {
fmt.Println("Missing filename argument")
fmt.Printf("Usage : %s filename\n", os.Args[0])
os.Exit(0)
}
fmt.Println(filename)
file, err := os.Open(filename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
buff := make([]byte, 512)
_, err = file.Read(buff)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
filetype := http.DetectContentType(buff)
fmt.Println("File type or MIME type : ", filetype)
}
Sample output :
img.gif
File type or MIME type : image/gif
img.pdf
File type or MIME type : application/pdf
Reference :
See also : Golang : How to verify uploaded file is image or allowed file types
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.3k Generate Random number with math/rand in Go
+11.2k Golang : How to check if a string starts or ends with certain characters or words?
+5.9k Golang : Calculate BMI and risk category
+3.1k Detect if Google Analytics and Developer Media are loaded properly or not
+7.8k Golang : Heap sort example
+12.5k Golang : unknown escape sequence error
+8.4k Golang : Quadratic example
+26.5k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+20.1k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+11k Golang : Encrypt and decrypt data with x509 crypto
+4.7k Javascript : How to refresh page with JQuery ?