Skip to content

Instantly share code, notes, and snippets.

@ivarprudnikov
Created February 27, 2023 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivarprudnikov/7a4eb0ddc2aaf67efba9ad44f832a257 to your computer and use it in GitHub Desktop.
Save ivarprudnikov/7a4eb0ddc2aaf67efba9ad44f832a257 to your computer and use it in GitHub Desktop.
Send multipart form data in go
package main
import (
"bytes"
"mime/multipart"
"net/http"
)
func PostFormMultipart(content []byte) (*http.Response, error) {
url := "http://localhost:8080"
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("fieldname", "filename.txt")
if err != nil {
return nil, err
}
part.Write(content)
err = writer.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
return http.DefaultClient.Do(req)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment