Skip to content

Instantly share code, notes, and snippets.

@easyforgood
Created July 3, 2020 02:39
Show Gist options
  • Save easyforgood/0a82550cdf64bed14c0fb06b41c628d7 to your computer and use it in GitHub Desktop.
Save easyforgood/0a82550cdf64bed14c0fb06b41c628d7 to your computer and use it in GitHub Desktop.
Golang http detect file type
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
// Open File
f, err := os.Open("golangcode.pdf")
if err != nil {
panic(err)
}
defer f.Close()
// Get the content
contentType, err := GetFileContentType(f)
if err != nil {
panic(err)
}
fmt.Println("Content Type: " + contentType)
}
func GetFileContentType(out *os.File) (string, error) {
// Only the first 512 bytes are used to sniff the content type.
buffer := make([]byte, 512)
_, err := out.Read(buffer)
if err != nil {
return "", err
}
// Use the net/http package's handy DectectContentType function. Always returns a valid
// content-type by returning "application/octet-stream" if no others seemed to match.
contentType := http.DetectContentType(buffer)
return contentType, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment