-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathform.go
65 lines (57 loc) · 1.14 KB
/
form.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
)
type FormDataMap map[string]io.Reader
func (fdm FormDataMap) Upload(url string) error {
// Prepare a form that will be submitted to the url
var (
b = bytes.Buffer{}
client = http.Client{}
)
mpw := multipart.NewWriter(&b)
for key, rdr := range fdm {
var wrtr io.Writer
if clsr, ok := rdr.(io.Closer); ok {
defer clsr.Close()
}
// Add the file
if file, ok := rdr.(*os.File); ok {
w, err := mpw.CreateFormFile(key, file.Name())
if err != nil {
return err
}
wrtr = w
} else {
// Add other fields
w, err := mpw.CreateFormField(key)
if err != nil {
return err
}
wrtr = w
}
_, err := io.Copy(wrtr, rdr)
if err != nil {
return err
}
}
mpw.Close()
req, err := http.NewRequest(http.MethodPost, url, &b)
if err != nil {
return err
}
req.Header.Set(HTTPHeaderContentType, mpw.FormDataContentType())
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("expected %d status code, but got %d", http.StatusOK, resp.StatusCode)
}
return nil
}