如何在Go语言中检测文件的类型?


考虑这样一种情况:出于某种原因,我们希望在Go语言中获取文件的类型。为此,我们首先必须知道如何打开文件并将部分字节读取到缓冲区切片中,然后将其传递给一个函数,该函数将帮助我们检测文件的类型。

第一步是打开我们要检查其类型的文件。

打开文件

假设我们有一个名为**sample.pdf**的文件,我们想知道它的**contentType**。为了打开文件,我们需要按照下面代码片段中所示的代码进行操作。

// 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

更新于:2021年11月1日

6K+浏览量

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.