Last active
August 5, 2025 07:22
-
-
Save wjkoh/1436020724871ceaa17cc65877fa7fc6 to your computer and use it in GitHub Desktop.
Go: Detect Content Type or MIIME 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 ( | |
| "io" | |
| "log" | |
| "net/http" | |
| "os" | |
| ) | |
| func detectContentType(r io.Reader) (string, error) { | |
| data := make([]byte, 512) | |
| n, err := r.Read(data) | |
| // NOTE: io.EOF is normal when len(data) < 512. | |
| if err != nil && err != io.EOF { | |
| return "", err | |
| } | |
| // NOTE: date[:n] is important when len(data) < 512. | |
| return http.DetectContentType(data[:n]), nil | |
| } | |
| func main() { | |
| const filename = "input.file" | |
| f, err := os.Open(filename) | |
| if err != nil { | |
| return log.Fatal(err) | |
| } | |
| defer f.Close() | |
| contentType, err := detectContentType(f) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| log.Println(contentType) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment