Go standard library facility to check file type for xlsx file gives something like this
import (
"fmt"
"log"
"net/http"
"os"
)
func main() {
f, err := os.Open("file_c.xlsx")
if err != nil {
log.Fatal(err.Error())
}
defer f.Close()
buf := make([]byte, 512)
_, err = f.Read(buf)
if err != nil {
log.Fatal(err.Error())
}
contentType := http.DetectContentType(buf)
fmt.Println(contentType)
}
and that prints:
application/zip
This package -> https://github.com/h2non/filetype
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/h2non/filetype"
)
func main() {
buf, _ := ioutil.ReadFile("file_c.xlsx")
kind, _ := filetype.Match(buf)
if kind == filetype.Unknown {
fmt.Println("unknown")
return
}
fmt.Printf("file type %s. MIME %s\n", kind.Extension, kind.MIME.Value)
}
prints:
file type xlsx. MIME application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
However when I have code like this:
// where file is of type *multipart.FileHeader
mpf, err := file.Open()
if err != nil {
wlog.Errorf("could not open %s file", file.Filename)
} else {
defer mpf.Close()
}
buf := make([]byte, 512)
_, err = mpf.Read(buf)
if err != nil {
wlog.Error("failed to read file")
} else {
kind, _ := filetype.Match(buf)
if kind == filetype.Unknown {
wlog.Info("unknown file type")
} else {
wlog.Infof("file type %s. MIME %s\n", kind.Extension, kind.MIME.Value)
}
}
prints:
file type zip. MIME application/zip
so information about xlsx file is lost somewhere in the middle even when I use this external code -> https://github.com/h2non/filetype Do you have any idea why or what am I doing wrong?