如何在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.