How to Merge Two DOCX Documents Together using Go

Cloudmersive
2 min readNov 28, 2022

--

Assembling consolidated DOCX files from a variety of separate DOCX documents typically entails a multi-step, manual “point-and-click” process. Taking advantage of our Merge DOCX Document API can make this administrative process much simpler; with the ready-to-run Golang code examples provided below in this article, you can easily combine two DOCX files with a single API call. You can use this API completely free, too — all you need is a free-tier Cloudmersive API key (you can get one by registering a free account on our website).

To structure your API call, simply copy the below examples into your file, and include your file inputs & API key in their respective fields:

package main

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

func main() {

url := "https://api.cloudmersive.com/convert/merge/docx"
method := "POST"

payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("/path/to/file")
defer file.Close()
part1,
errFile1 := writer.CreateFormFile("inputFile1",filepath.Base("/path/to/file"))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
fmt.Println(errFile1)
return
}
file, errFile2 := os.Open("/path/to/file")
defer file.Close()
part2,
errFile2 := writer.CreateFormFile("inputFile2",filepath.Base("/path/to/file"))
_, errFile2 = io.Copy(part2, file)
if errFile2 != nil {
fmt.Println(errFile2)
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))
}

That’s all there is to it!

--

--

Cloudmersive

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