2 | 2 |
import (
|
3 | 3 |
"bytes"
|
4 | 4 |
"encoding/json"
|
5 | |
"errors"
|
6 | 5 |
"fmt"
|
7 | 6 |
"io"
|
8 | 7 |
"io/ioutil"
|
|
41 | 40 |
return string(s)
|
42 | 41 |
}
|
43 | 42 |
|
44 | |
func fileUploadReq(path, fpath, fieldname string, values url.Values) (*http.Request, error) {
|
45 | |
fullpath, err := filepath.Abs(fpath)
|
46 | |
if err != nil {
|
47 | |
return nil, err
|
48 | |
}
|
49 | |
file, err := os.Open(fullpath)
|
50 | |
if err != nil {
|
51 | |
return nil, err
|
52 | |
}
|
53 | |
defer file.Close()
|
54 | |
|
|
43 |
func fileUploadReq(path, fieldname, filename string, values url.Values, r io.Reader) (*http.Request, error) {
|
55 | 44 |
body := &bytes.Buffer{}
|
56 | 45 |
wr := multipart.NewWriter(body)
|
57 | 46 |
|
58 | |
ioWriter, err := wr.CreateFormFile(fieldname, filepath.Base(fullpath))
|
|
47 |
ioWriter, err := wr.CreateFormFile(fieldname, filename)
|
59 | 48 |
if err != nil {
|
60 | 49 |
wr.Close()
|
61 | 50 |
return nil, err
|
62 | 51 |
}
|
63 | |
bytes, err := io.Copy(ioWriter, file)
|
|
52 |
_, err = io.Copy(ioWriter, r)
|
64 | 53 |
if err != nil {
|
65 | 54 |
wr.Close()
|
66 | 55 |
return nil, err
|
67 | 56 |
}
|
68 | 57 |
// Close the multipart writer or the footer won't be written
|
69 | 58 |
wr.Close()
|
70 | |
stat, err := file.Stat()
|
71 | |
if err != nil {
|
72 | |
return nil, err
|
73 | |
}
|
74 | |
if bytes != stat.Size() {
|
75 | |
return nil, errors.New("could not read the whole file")
|
76 | |
}
|
77 | 59 |
req, err := http.NewRequest("POST", path, body)
|
78 | 60 |
if err != nil {
|
79 | 61 |
return nil, err
|
|
102 | 84 |
return nil
|
103 | 85 |
}
|
104 | 86 |
|
105 | |
func postWithMultipartResponse(path, filepath, fieldname string, values url.Values, intf interface{}, debug bool) error {
|
106 | |
req, err := fileUploadReq(SLACK_API+path, filepath, fieldname, values)
|
|
87 |
func postLocalWithMultipartResponse(path, fpath, fieldname string, values url.Values, intf interface{}, debug bool) error {
|
|
88 |
fullpath, err := filepath.Abs(fpath)
|
|
89 |
if err != nil {
|
|
90 |
return err
|
|
91 |
}
|
|
92 |
file, err := os.Open(fullpath)
|
|
93 |
if err != nil {
|
|
94 |
return err
|
|
95 |
}
|
|
96 |
defer file.Close()
|
|
97 |
return postWithMultipartResponse(path, filepath.Base(fpath), fieldname, values, file, intf, debug)
|
|
98 |
}
|
|
99 |
|
|
100 |
func postWithMultipartResponse(path, name, fieldname string, values url.Values, r io.Reader, intf interface{}, debug bool) error {
|
|
101 |
req, err := fileUploadReq(SLACK_API+path, fieldname, name, values, r)
|
107 | 102 |
if err != nil {
|
108 | 103 |
return err
|
109 | 104 |
}
|