How to Convert a Video File to MP4 in Go

The compressible nature of the MP4 format is ideal for the streaming and downloading of videos, which as you may expect, has made it incredibly prevalent in the video editing world. If you need to improve the quality or accessibility of various video files, switching them over to the MP4 format is a smart move. In this brief tutorial, we will demonstrate how you can use an API in Go to automatically detect a video file format and convert it to MP4.

For this particular API, the only required inputs are the video file and API key; however there are several optional parameters you can specify including height, width, aspect ratio, frame rate, and quality level. Now, to call the conversion function, simply add your inputs to the following code:

package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)
func main() {url := "https://api.cloudmersive.com/video/convert/to/mp4"
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("fileUrl", "<string>")
req.Header.Add("maxWidth", "<integer>")
req.Header.Add("maxHeight", "<integer>")
req.Header.Add("preserveAspectRatio", "<boolean>")
req.Header.Add("frameRate", "<integer>")
req.Header.Add("quality", "<integer>")
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))
}

This will use 1 API call per 10 MB of file size, as well as 1 API call per additional minute of processing time over 5 minutes, up to a maximum of 25 minutes total processing time. Visit the Cloudmersive website to retrieve your API key by registering for a free account; this will provide access to 800 calls/month across our entire library of APIs.