Created
February 27, 2023 15:36
-
-
Save ivarprudnikov/7a4eb0ddc2aaf67efba9ad44f832a257 to your computer and use it in GitHub Desktop.
Send multipart form data in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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