create an http post request sending multipart form data in go

Here's an example code snippet for creating an HTTP POST request sending multipart form data in Go:

main.go
// create a new multipart buffer to hold form data
var b bytes.Buffer
w := multipart.NewWriter(&b)

// add a file field
fileWriter, err := w.CreateFormFile("file", "example.txt")
if err != nil {
    // handle error
}
file, err := os.Open("example.txt")
if err != nil {
    // handle error
}
defer file.Close()
_, err = io.Copy(fileWriter, file)
if err != nil {
    // handle error
}

// add a field with some data
textFieldWriter, err := w.CreateFormField("textField")
if err != nil {
    // handle error
}
textFieldWriter.Write([]byte("some text"))

// don't forget to close the multipart writer
err = w.Close()
if err != nil {
    // handle error
}

// create an HTTP POST request with the multipart form data
req, err := http.NewRequest("POST", url, &b)
if err != nil {
    // handle error
}
req.Header.Set("Content-Type", w.FormDataContentType())

// send the request and get the response
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    // handle error
}
defer resp.Body.Close()

// do something with the response
1043 chars
49 lines

In this example, we first create a new multipart buffer using the multipart.NewWriter() function from the mime/multipart package. We then add a file field and a text field to the multipart buffer using the CreateFormFile() and CreateFormField() methods of the multipart writer. Finally, we close the multipart writer and create an HTTP POST request with the multipart form data using http.NewRequest(). We set the Content-Type header of the request to multipart/form-data, which is the correct MIME type for sending multipart form data. We then send the request using an http.Client and get the response in the usual way.

related categories

gistlibby LogSnag