Created
July 3, 2020 02:39
-
-
Save easyforgood/0a82550cdf64bed14c0fb06b41c628d7 to your computer and use it in GitHub Desktop.
Golang http detect file type
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
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