Skip to content

Instantly share code, notes, and snippets.

@ivanlemeshev
Forked from rayrutjes/detectcontenttype.go
Created January 30, 2017 10:58
Show Gist options
  • Save ivanlemeshev/ea784cc85a4e7ac073f1f07c38586295 to your computer and use it in GitHub Desktop.
Save ivanlemeshev/ea784cc85a4e7ac073f1f07c38586295 to your computer and use it in GitHub Desktop.
golang detect content type of a file
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
// Only the first 512 bytes are used to sniff the content type.
buffer := make([]byte, 512)
_, err = file.Read(buffer)
if err != nil {
return err
}
// Reset the read pointer if necessary.
file.Seek(0, 0)
// Always returns a valid content-type and "application/octet-stream" if no others seemed to match.
contentType := http.DetectContentType(buffer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment