How to Scan Files, Set Custom File Upload Restrictions in Go

Cloudmersive
2 min readJun 21, 2023

--

Scanning files for viruses and malware is a top priority for any website implementing client-side file upload processes. It doesn’t end there, however. Other security measures — such as blocking common hidden threat types and restricting file uploads — are equally important to keep your applications safe.

Thankfully, using the ready-to-run Golang code examples below, you can scan files for millions of virus and malware signatures, block common hidden threat types, and set custom restrictions against unwanted file types with a comma-separated list of file extensions (such as “.pdf, .docx, .xlsx”) — all in a single API request. This solution is free to use with a free-tier Cloudmersive API key, and you can get set up in minutes.

Simply copy the following code to structure your API call:

package main

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

func main() {

url := "https://api.cloudmersive.com/virus/scan/file/advanced"
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("allowExecutables", "<boolean>")
req.Header.Add("allowInvalidFiles", "<boolean>")
req.Header.Add("allowScripts", "<boolean>")
req.Header.Add("allowPasswordProtectedFiles", "<boolean>")
req.Header.Add("allowMacros", "<boolean>")
req.Header.Add("allowXmlExternalEntities", "<boolean>")
req.Header.Add("allowInsecureDeserialization", "<boolean>")
req.Header.Add("allowHtml", "<boolean>")
req.Header.Add("restrictFileTypes", "<string>")
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))
}

Provide your file extension whitelist in the “restrictFileTypes” parameter, and then customize any addiitonal content threat rules to your liking. Easy!

--

--

Cloudmersive

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