/
http.go
69 lines (58 loc) · 1.32 KB
/
http.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
66
67
68
69
package utils
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
// ErrUploadFile error message when upload file failed
var ErrUploadFile = "upload file failed: URL(%s)\nfilename(%s)\nmessage(%s)"
// PostFile post file to targetUrl
func PostFile(fileParam, filePath string, extraParams map[string]string, targetURL string) error {
bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)
var (
fileWriter io.Writer
fh *os.File
resp *http.Response
output []byte
err error
)
// this step is very important
fileWriter, err = bodyWriter.CreateFormFile(fileParam, filepath.Base(filePath))
if err != nil {
return err
}
// open file handle
fh, err = os.Open(filePath)
if err != nil {
return err
}
//iocopy
_, err = io.Copy(fileWriter, fh)
if err != nil {
return err
}
contentType := bodyWriter.FormDataContentType()
// add params
if extraParams != nil {
for k, v := range extraParams {
bodyWriter.WriteField(k, v)
}
}
bodyWriter.Close()
resp, err = http.Post(targetURL, contentType, bodyBuf)
if err != nil {
return err
}
defer resp.Body.Close()
output, err = ioutil.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return fmt.Errorf(ErrUploadFile, targetURL, filePath, string(output))
}
return err
}