How to Validate a Common Image File Format using Golang

Cloudmersive
2 min readDec 2, 2022

--

If your website is accepting a wide variety of image formats for upload, you’ll need a data validation service that can keep up. Our Validate Image File API supports dozens of common image formats — including JPG, PNG, GIF, etc. — and quickly returns a Boolean value indicating if the file in question is valid or incorrectly formatted. Along with this Boolean response, this API will determine if the file is password protected (a big red flag!) and supply both an error and warning count with descriptions for each.

To build this API into your application, all you need to do is copy the Golang code examples below into your environment and validate the service with a Cloudmersive API key (which you can get by registering a free account on our website; free-tier keys supply a limit of 800 API calls per month). Add your key & file inputs in their respective (labeled) fields, and you’re ready to make your call:

package main

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

func main() {

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

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