How to Upload a File with HTTP in Go (Multipart)

Web
Upload a file in Go using the mime/multipart package to create a multipart/form-data HTTP POST request.

Use mime/multipart to create a Request with Content-Type: multipart/form-data and write the file to the body.

package main

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

func main() {
	file, _ := os.Open("file.txt")
	defer file.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	part, _ := writer.CreateFormFile("file", "file.txt")
	io.Copy(part, file)

	writer.Close()

	req, _ := http.NewRequest("POST", "http://example.com/upload", body)
	req.Header.Set("Content-Type", writer.FormDataContentType())

	client := &http.Client{}
	resp, _ := client.Do(req)
	defer resp.Body.Close()

	fmt.Println(resp.Status)
}