Created
December 12, 2015 13:36
-
-
Save rayrutjes/db9b9ea8e02255d62ce2 to your computer and use it in GitHub Desktop.
golang detect content type of a file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Cool