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
+12.2k Golang : Split strings into command line arguments
+5.6k Swift : Get substring with rangeOfString() function example
+8.3k Useful methods to access blocked websites
+8.8k Golang : Accept any number of function arguments with three dots(...)
+15.6k Golang : ROT47 (Caesar cipher by 47 characters) example
+7.4k Golang : Word limiter example
+5k Google : Block or disable caching of your website content
+14.8k Golang : Normalize unicode strings for comparison purpose
+12.4k Golang : Encrypt and decrypt data with x509 crypto
+16.3k Golang :Trim white spaces from a string
+14k Golang : convert rune to unicode hexadecimal value and back to rune character
+7k Golang : Gargish-English language translator