Skip to content

Instantly share code, notes, and snippets.

@wjkoh
Last active August 5, 2025 07:22
Show Gist options
  • Select an option

  • Save wjkoh/1436020724871ceaa17cc65877fa7fc6 to your computer and use it in GitHub Desktop.

Select an option

Save wjkoh/1436020724871ceaa17cc65877fa7fc6 to your computer and use it in GitHub Desktop.
Go: Detect Content Type or MIIME Type
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