How to Validate a CSV in Go

Cloudmersive
2 min readApr 19, 2021

By definition, a comma-separated values (CSV) file is a delimited text file that uses a comma to separate values; each line holds a data record which consists of plain text, and they are organized into columns and rows. The CSV format is commonly used to move tabular data, but unfortunately due to the innate nuances of its design, a single typo can skew data and cause errors. To avoid the research that often accompanies such errors, you can use the following API in Go to automatically validate a CSV file; if the document is invalid, the API will identify the errors.

To perform the validation, we will simply call the function with the following code:

package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)
func main() {url := "https://api.cloudmersive.com/convert/validate/csv"
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))
}

At the end of this process, you will be notified of the valid status of your document! To retrieve your API key, you can register for a free account on the Cloudmersive website; this will give you access to 800 calls/month across our library of APIs.

--

--

Cloudmersive

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