forked from hugozhu/godingtalk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtop_api_request.go
88 lines (75 loc) · 1.8 KB
/
top_api_request.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
/*
* Author Kevin Zhu
*
* Direct questions, comments to <[email protected]>
*/
package godingtalk
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
)
const (
topAPIRootURL = "https://eco.taobao.com/router/rest"
formDataType = "application/x-www-form-urlencoded;charset=utf-8"
)
type TopAPIResponse interface {
checkError() error
}
type topAPIErrResponse struct {
ERR struct {
Code int `json:"code"`
Msg string `json:"msg"`
SubCode string `json:"sub_code"`
SubMsg string `json:"sub_msg"`
RequestID string `json:"request_id"`
} `json:"error_response"`
}
func (data *topAPIErrResponse) checkError() (err error) {
if data.ERR.Code != 0 || len(data.ERR.SubCode) != 0 {
err = fmt.Errorf("%#v", data.ERR)
}
return err
}
func (c *DingTalkClient) topAPIRequest(requestForm url.Values, respData TopAPIResponse) error {
requestForm.Set("v", "2.0")
requestForm.Set("format", "json")
requestForm.Set("simplify", "true")
err := c.RefreshAccessToken()
if err != nil {
return err
}
requestForm.Set("session", c.AccessToken)
if requestForm.Get("timestamp") == "" {
requestForm.Set("timestamp", time.Now().Format("2006-01-02 15:04:05"))
}
if c.PartnerID != "" {
requestForm.Set("partner_id", c.PartnerID)
}
v := bytes.NewBuffer([]byte(requestForm.Encode()))
req, _ := http.NewRequest("POST", topAPIRootURL, v)
req.Header.Set("Content-Type", formDataType)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New("Server error: " + resp.Status)
}
defer resp.Body.Close()
buf, err := ioutil.ReadAll(resp.Body)
if err == nil {
err := json.Unmarshal(buf, &respData)
if err != nil {
return err
}
return respData.checkError()
}
return err
}