-
Notifications
You must be signed in to change notification settings - Fork 4
/
sendcloud.go
99 lines (84 loc) · 2.08 KB
/
sendcloud.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
package sendcloud
import (
"bytes"
"encoding/json"
"errors"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"strings"
)
type Client struct {
apiUser string
apiKey string
Client *http.Client
}
func New(apiUser, apiKey string) *Client {
var c = &Client{}
c.apiUser = apiUser
c.apiKey = apiKey
c.Client = http.DefaultClient
return c
}
// doRequest 发起网络请求
func (this *Client) doRequest(url string, values url.Values, result interface{}) error {
if len(this.apiKey) == 0 || len(this.apiUser) == 0 {
return errors.New("请先配置 api 信息")
}
values.Add("apiUser", this.apiUser)
values.Add("apiKey", this.apiKey)
rsp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(values.Encode()))
if err != nil {
return err
}
defer rsp.Body.Close()
bodyBytes, err := io.ReadAll(rsp.Body)
if err != nil {
return err
}
return json.Unmarshal(bodyBytes, result)
}
func (this *Client) doRequestWithFile(url string, values url.Values, fieldname string, filenames []string, result interface{}) error {
if len(this.apiKey) == 0 || len(this.apiUser) == 0 {
return errors.New("请先配置 api 信息")
}
values.Add("apiUser", this.apiUser)
values.Add("apiKey", this.apiKey)
var bodyBuffer = &bytes.Buffer{}
var bodyWriter = multipart.NewWriter(bodyBuffer)
for _, filename := range filenames {
fileContent, err := os.ReadFile(filename)
if err != nil {
return err
}
fileWriter, err := bodyWriter.CreateFormFile(fieldname, filename)
if err != nil {
return err
}
if _, err = fileWriter.Write(fileContent); err != nil {
return err
}
}
for key, value := range values {
for _, v := range value {
_ = bodyWriter.WriteField(key, v)
}
}
if err := bodyWriter.Close(); err != nil {
return err
}
req, err := http.NewRequest("POST", url, bodyBuffer)
req.Header.Set("Content-Type", bodyWriter.FormDataContentType())
rsp, err := this.Client.Do(req)
if err != nil {
return err
}
defer rsp.Body.Close()
bodyBytes, err := io.ReadAll(rsp.Body)
if err != nil {
return err
}
return json.Unmarshal(bodyBytes, result)
}