-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathresponse.go
67 lines (63 loc) · 1.42 KB
/
response.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
package weixinmp
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
// response from weixinmp
type response struct {
// error fields
ErrCode int64 `json:"errcode"`
ErrMsg string `json:"errmsg"`
// token fields
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
// media fields
Type string `json:"type"`
MediaId string `json:"media_id"`
CreatedAt int64 `json:"created_at"`
// ticket fields
Ticket string `json:"ticket"`
ExpireSeconds int64 `json:"expire_seconds"`
}
func post(url string, bodyType string, body *bytes.Buffer) (*response, error) {
resp, err := http.Post(url, bodyType, body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var rtn response
if err := json.Unmarshal(data, &rtn); err != nil {
return nil, err
}
if rtn.ErrCode != 0 {
return nil, errors.New(fmt.Sprintf("%d %s", rtn.ErrCode, rtn.ErrMsg))
}
return &rtn, nil
}
func get(url string) (*response, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var rtn response
if err := json.Unmarshal(data, &rtn); err != nil {
return nil, err
}
if rtn.ErrCode != 0 {
return nil, errors.New(fmt.Sprintf("%d %s", rtn.ErrCode, rtn.ErrMsg))
}
return &rtn, nil
}