How to Get Document Type Information using Go
When identifying different file types in our applications, we can principally rely on two signals: the file extension, or the encoding of the file itself. Where file extensions aren’t readily available, it’s great to have a way of identifying files through the latter method, and that’s where our Get Document Type Information API makes a big difference. This API will reliably detect the contents of a file and identify the file type with no file extension required; it can detect more than 100 different image file formats, office document file formats, PDFs, and more. Successfully calling this API will return a haul of important information (demonstrated here in JSON format):
{
"Successful": true,
"DetectedFileExtension": "string",
"DetectedMimeType": "string",
"PageCount": 0,
"Author": "string",
"DateModified": "2022-11-14T17:06:04.282Z",
"AlternateFileTypeCandidates": [
{
"Probability": 0,
"DetectedFileExtension": "string",
"DetectedMimeType": "string"
}
]
}
It’s really simple & easy to use this API — all you need to do is register a free account on our website (this will provide an API key with a limit of 800 API calls per month) and copy & paste the Go code examples provided below to structure your API call.
To call this API, all we need to do is copy the below code, include our API key in the correct field (shown in the code comments), and we’re all set:
package main
import (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)
func main() {
url := "https://api.cloudmersive.com/convert/autodetect/get-info"
method := "POST"
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("/path/to/file")
defer file.Close()
part1,
errFile1 := writer.CreateFormFile("inputFile",filepath.Base("/path/to/file"))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
fmt.Println(errFile1)
return
}
err := writer.Close()
if err != nil {
fmt.Println(err)
return
}
client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "multipart/form-data")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")
req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
And that’s really it — no more code is required. Now you can easily detect file types in the blink of an eye!