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
+20.9k Golang : Get password from console input without echo or masked
+17.9k Golang : Put UTF8 text on OpenCV video capture image frame
+4.7k Nginx and PageSpeed build from source CentOS example
+7.6k Golang : Generate human readable password
+12.1k Golang : Display list of countries and ISO codes
+6k Golang : Extract XML attribute data with attr field tag example
+10.8k Golang : Create Temporary File
+18.2k Golang : Read binary file into memory
+7.6k Golang : Load DSA public key from file example
+13.2k Android Studio : Password input and reveal password example
+22.3k Golang : Convert Unix timestamp to UTC timestamp
+13.2k Golang : error parsing regexp: invalid or unsupported Perl syntax