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
+5.3k Python : Convert(cast) string to bytes example
+28.5k Golang : Change a file last modified date and time
+10.3k Golang : How to check if a website is served via HTTPS
+22.4k Golang : Read directory content with filepath.Walk()
+12.5k Golang : "https://" not allowed in import path
+47.8k Golang : Convert int to byte array([]byte)
+80.7k Golang : How to return HTTP status code?
+12k Golang : Convert a rune to unicode style string \u
+5.6k PHP : Convert CSV to JSON with YQL example
+12.3k Golang : Get month name from date example
+7.5k Gogland : Single File versus Go Application Run Configurations
+10.8k Golang : Command line file upload program to server example