Golang 如何检测一个文件的内容类型
考虑到我们想在Golang中获得一个文件的内容类型,无论出于什么原因。为了做到这一点,我们必须首先知道如何打开该文件,并将其部分字节读入一个缓冲区片,然后我们将其传递给一个函数,以帮助我们检测文件的类型。
第1步是打开我们想检查其类型的文件。
打开文件
考虑到我们有一个名为 sample.pdf 的文件,其 内容类型 是我们想知道的。为了打开该文件,我们需要按照下面的代码片段所示进行操作。
// Open the file whose type you
// want to check
file, err := os.Open("sample.pdf")
if err != nil {
panic(err)
}
defer file.Close()
在上面的片段中,我们正在打开一个名为 sample.pdf 的文件,然后如果我们遇到任何错误,我们将调用 panic 函数。
注意,我们还推迟了文件的 Close() 方法,这总是一个好的做法。
从文件中读取数据
下一步是从文件中读取数据,我们可以在 os 包中的 Read() 方法的帮助下做到这一点。
下面所示的代码片段表示我们如何从文件中读取数据,然后将其存储在一个缓冲区中供以后使用。
// to sniff the content type only the first
// 512 bytes are used.
buf := make([]byte, 512)
_, err := out.Read(buf)
if err != nil {
return "", err
}
检测内容类型
现在,最后一步是调用 http 包为我们提供的 DetectContentType() 函数。
下面是完整的程序代码 –
package main
import (
"fmt"
"net/http"
"os"
)
func main() {
// Open the file whose type you
// want to check
file, err := os.Open("sample.pdf")
if err != nil {
panic(err)
}
defer file.Close()
// Get the file content
contentType, err := GetFileContentType(file)
if err != nil {
panic(err)
}
fmt.Println("Content Type of file is: " + contentType)
}
func GetFileContentType(ouput *os.File) (string, error) {
// to sniff the content type only the first
// 512 bytes are used.
buf := make([]byte, 512)
_, err := ouput.Read(buf)
if err != nil {
return "", err
}
// the function that actually does the trick
contentType := http.DetectContentType(buf)
return contentType, nil
}
输出
如果我们在上述代码上运行命令 go run main.go ,那么我们将在终端得到以下输出。
Content Type: application/pdf
极客教程