How to Autodetect Content Type & Validate using Go
Validation steps play an important role within any application, ensuring incorrectly formatted data doesn’t move downstream and cause potentially significant problems/delays in production. By taking advantage of our Autodetect Content & Validate API, you’ll reap the benefits of a built-in service capable of instantly determining the type and validity of various documents’ contents. In its response, this API will identify the input file format’s extension and supply a Boolean value indicating if the document is valid or not. If any issues were found within the document, the response will indicate exactly how many errors and warnings were detected and provide a description (if available) for both.
With the complementary, ready-to-run Golang code examples provided below in this article, you can quickly and easily build this API into your application. All you need is a valid Cloudmersive API key to authenticate the service (you can get one by registering a free account on our website) and you’re ready to make your API call.
To structure your API call, include the below code in your environment, and supply your API key & file path in their respective fields:
package main
import (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)
func main() {
url := "https://api.cloudmersive.com/convert/validate/autodetect"
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))
}