Created
July 5, 2022 13:46
-
-
Save slav123/8d3b258cfa5ad4bfdc571248db76f718 to your computer and use it in GitHub Desktop.
Send multipart/form-data form with GO
This file contains hidden or 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
type field struct { | |
Key string `json:"key"` | |
Value string `json:"value"` | |
} | |
func Post(url string, fields []field) error { | |
var b bytes.Buffer | |
w := multipart.NewWriter(&b) | |
var ( | |
fw io.Writer | |
err error | |
) | |
for _, f := range fields { | |
if f.Key == "file" { | |
fw, err = w.CreateFormFile(f.Key, filepath.Base(f.Value)) | |
fd, err := os.Open(filepath.Base(f.Value)) | |
if err != nil { | |
log.Println("Open file failed:", err) | |
return err | |
} else { | |
_, err = io.Copy(fw, fd) | |
fd.Close() | |
if err != nil { | |
log.Println("Copy file failed:", err) | |
return err | |
} | |
} | |
} else { | |
fw, err = w.CreateFormField(f.Key) | |
if err != nil { | |
return err | |
} | |
if _, err := fw.Write([]byte(f.Value)); err != nil { | |
return err | |
} | |
} | |
} | |
w.Close() | |
req, err := http.NewRequest("POST", url, &b) | |
if err != nil { | |
return err | |
} | |
req.Header.Set("Content-Type", w.FormDataContentType()) | |
client := &http.Client{} | |
res, err := client.Do(req) | |
if err != nil { | |
return err | |
} | |
if res.StatusCode != http.StatusOK { | |
fmt.Printf("error post: %s\n", res.Status) | |
err = fmt.Errorf("bad status: %s", res.Status) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment