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
+16k Golang : Get sub string example
+5.7k Get website traffic ranking with Similar Web or Alexa
+12.7k Golang : zlib compress file example
+13.6k Golang : Query string with space symbol %20 in between
+32.2k Golang : Convert []string to []byte examples
+8.6k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+30.6k Golang : Remove characters from string example
+14.6k Golang : Reset buffer example
+24.5k Golang : How to validate URL the right way
+5.2k Golang : Experimental Jawi programming language
+10.1k Golang : Identifying Golang HTTP client request
+5.6k Swift : Get substring with rangeOfString() function example