forked from slack-go/slack
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmisc.go
107 lines (97 loc) · 2.45 KB
/
misc.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package slack
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
)
func fileUploadReq(path, fpath string, values url.Values) (*http.Request, error) {
fullpath, err := filepath.Abs(fpath)
if err != nil {
return nil, err
}
file, err := os.Open(fullpath)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
wr := multipart.NewWriter(body)
ioWriter, err := wr.CreateFormFile("file", filepath.Base(fullpath))
if err != nil {
wr.Close()
return nil, err
}
bytes, err := io.Copy(ioWriter, file)
if err != nil {
wr.Close()
return nil, err
}
// Close the multipart writer or the footer won't be written
wr.Close()
stat, err := file.Stat()
if err != nil {
return nil, err
}
if bytes != stat.Size() {
return nil, errors.New("could not read the whole file")
}
req, err := http.NewRequest("POST", path, body)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", wr.FormDataContentType())
req.URL.RawQuery = (values).Encode()
return req, nil
}
func parseResponseBody(body io.ReadCloser, intf *interface{}, debug bool) error {
var decoder *json.Decoder
if debug {
response, err := ioutil.ReadAll(body)
if err != nil {
return err
}
log.Println(string(response))
decoder = json.NewDecoder(bytes.NewReader(response))
} else {
decoder = json.NewDecoder(body)
}
if err := decoder.Decode(&intf); err != nil {
return err
}
return nil
}
func parseResponseMultipart(path string, filepath string, values url.Values, intf interface{}, debug bool) error {
req, err := fileUploadReq(SLACK_API+path, filepath, values)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return parseResponseBody(resp.Body, &intf, debug)
}
func postForm(endpoint string, values url.Values, intf interface{}, debug bool) error {
resp, err := http.PostForm(endpoint, values)
if err != nil {
return err
}
defer resp.Body.Close()
return parseResponseBody(resp.Body, &intf, debug)
}
func parseResponse(path string, values url.Values, intf interface{}, debug bool) error {
return postForm(SLACK_API+path, values, intf, debug)
}
func parseAdminResponse(method string, teamName string, values url.Values, intf interface{}, debug bool) error {
endpoint := fmt.Sprintf(SLACK_WEB_API_FORMAT, teamName, method, time.Now().Unix())
return postForm(endpoint, values, intf, debug)
}