Golang net/http.DetectContentType() function examples
package net/http
Golang net/http.DetectContentType() function usage examples
Example 1:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
res, err := http.Get("https://d1ohg4ss876yi2.cloudfront.net/preview/golang.png")
if err != nil {
log.Fatal(err)
}
unknown, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
fileType := http.DetectContentType(unknown)
fmt.Println("FileType: ", fileType)
}
Example 2: ( from https://www.socketloop.com/tutorials/golang-how-to-verify-uploaded-file-is-image-or-allowed-file-types )
package main
import (
"fmt"
"net/http"
"os"
"runtime"
)
func main() {
// maximize CPU usage for maximum performance
runtime.GOMAXPROCS(runtime.NumCPU())
// open the uploaded file
file, err := os.Open("./img.png")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
buff := make([]byte, 512) // why 512 bytes ? see http://golang.org/pkg/net/http/#DetectContentType
_, err = file.Read(buff)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
filetype := http.DetectContentType(buff)
fmt.Println(filetype)
switch filetype {
case "image/jpeg", "image/jpg":
fmt.Println(filetype)
case "image/gif":
fmt.Println(filetype)
case "image/png":
fmt.Println(filetype)
case "application/pdf": // not image, but application !
fmt.Println(filetype)
default:
fmt.Println("unknown file type uploaded")
}
}
Reference :
Advertisement
Something interesting
Tutorials
+6.1k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+5.1k Swift : Convert (cast) Float to Int or Int32 value
+22.2k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+34.6k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+5.4k Golang : Reclaim memory occupied by make() example
+16.3k Golang : Find out mime type from bytes in buffer
+16.6k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+6.7k Golang : Check if password length meet the requirement
+13.1k Golang : Handle or parse date string with Z suffix(RFC3339) example
+12.3k Golang : Display list of countries and ISO codes
+13.3k Golang : Date and Time formatting
+8.1k Golang : Check from web if Go application is running or not