Skip to content

Instantly share code, notes, and snippets.

@kenng
Forked from rayrutjes/detectcontenttype.go
Created September 6, 2016 06:02
Show Gist options
  • Save kenng/fc860597983274a018e48ce8dc23b405 to your computer and use it in GitHub Desktop.
Save kenng/fc860597983274a018e48ce8dc23b405 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)
@kenng
Copy link
Author

kenng commented Sep 6, 2016

// function still work, if size of buffer < 512
n, err = file.Read(buffer)
if err != nil && err != io.EOF {
return err
}
contentType := http.DetectContentType(buffer[:n])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment