How to Validate a DOCX Document using Go

Cloudmersive
2 min readDec 2, 2022

--

Adding a validation step for your application’s DOCX upload field is critical; it ensures other common file types (such as PDF, RTF, etc.) can’t be mistakenly uploaded to your system and cause problems downstream. Our Validate DOCX API is designed to solve this problem in one fell swoop: it’s easy & free to use, and with a single API call, you can ensure invalid document types (or invalid DOCX encoding) is rejected at the outset of the file upload process. In its response, this API will first provide a Boolean value indicating the validity of the document in question, and after that, it will provide both an error & warning count if any additional issues were detected within the file itself.

To take advantage of this API within your application, all you need to do is copy the below code examples into your environment and authenticate your API call with a valid Cloudmersive API key (you can get one by registering a free account on our website). After that, you’re good to go — it’s just that simple!

package main

import (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)

func main() {

url := "https://api.cloudmersive.com/convert/validate/docx"
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))
}

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet