I\'m trying to upload images from my computer to a website using go. Usually, I use a bash script that sends a file and a key to the server:
curl -F \"image
Had the same issue in a unit test, and if you just need to send in a data to verify that the post this (below) was a little simpler for me. Hope it helps save someone else some time.
fileReader := strings.NewReader("log file contents go here")
b := bytes.Buffer{} // buffer to write the request payload into
fw := multipart.NewWriter(&b)
fFile, _ := fw.CreateFormFile("file", "./logfile.log")
io.Copy(fFile, fileReader)
fw.Close()
req, _ := http.NewRequest(http.MethodPost, url, &b)
req.Header.Set("Content-Type", fw.FormDataContentType())
resp, err := http.DefaultClient.Do(req)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
For me, fileReader is just a strings reader, because I'm posting a log file. In the case of a image, you would send the appropriate reader.