-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathmedia.go
78 lines (67 loc) · 1.72 KB
/
media.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
package wxworkbot
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/textproto"
"strings"
)
type uploadedMediaResponse struct {
wxWorkResponse
UploadedMedia
}
type UploadedMedia struct {
Type string `json:"type"'`
MediaID string `json:"media_id"`
CreatedAt string `json:"created_at"`
}
func uploadApiUrl(key *string) string {
return fmt.Sprintf(
"https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=%s&type=file",
*key,
)
}
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}
func (bot *WxWorkBot) UploadMedia(fileName string, fileBytes *[]byte) (*UploadedMedia, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="media"; filename="%s"; filelength=%d`,
escapeQuotes(fileName), len(*fileBytes)))
h.Set("Content-Type", "application/octet-stream")
part, err := writer.CreatePart(h)
if err != nil {
return nil, err
}
io.Copy(part, bytes.NewReader(*fileBytes))
writer.Close()
req, err := http.NewRequest(http.MethodPost, uploadApiUrl(&bot.Key), body)
req.Header.Add("Content-Type", writer.FormDataContentType())
if err != nil {
return nil, err
}
resp, err := bot.Client.Do(req)
if err != nil {
return nil, err
}
respBody, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
var wxWorkResp uploadedMediaResponse
err = json.Unmarshal(respBody, &wxWorkResp)
if err != nil {
return nil, err
}
if wxWorkResp.ErrorCode != 0 && wxWorkResp.ErrorMessage != "" {
return nil, errors.New(string(respBody))
}
return &wxWorkResp.UploadedMedia, nil
}