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
+14.5k Golang : Rename directory
+10.6k Golang : ISO8601 Duration Parser example
+9.5k Golang : Extract or copy items from map based on value
+12.3k Golang : Print UTF-8 fonts on image example
+6.8k Swift : substringWithRange() function example
+10.6k Golang : Allow Cross-Origin Resource Sharing request
+9.3k Golang : How to get ECDSA curve and parameters data?
+5.1k Linux : How to set root password in Linux Mint
+9.4k Golang : How to protect your source code from client, hosting company or hacker?
+5.9k Unix/Linux : How to open tar.gz file ?
+6.9k Default cipher that OpenSSL used to encrypt a PEM file
+8.3k Golang : Count leading or ending zeros(any item of interest) example