-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrequest.go
85 lines (69 loc) · 1.8 KB
/
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
package cns
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
//API响应的接口
type Responser interface {
Error() error
}
//基础的API响应结构
type BaseResponse struct {
Code int
Message string
CodeDesc string
}
//API响应中识别并构造API错误的方法
func (resp BaseResponse) Error() error {
if resp.Code == 0 {
return nil
}
return fmt.Errorf("[%d](%s): %s", resp.Code, resp.CodeDesc, resp.Message)
}
//云解析API请求的资源地址
const Uri = "cns.api.qcloud.com/v2/index.php"
//GET类型的API请求封装
func (cli *Client) requestGET(action string, param url.Values, respInfo interface{}) error {
return cli.request("GET", action, param, nil, respInfo)
}
//API请求的封装(内建公共参数、签名的设置)
func (cli *Client) request(method, action string, param url.Values, body io.Reader, respInfo interface{}) error {
if param == nil {
param = url.Values{}
}
//设置公共参数
param.Set("Action", action)
param.Set("Timestamp", fmt.Sprintf("%d", time.Now().Unix()))
param.Set("Nonce", "123456")
param.Set("SecretId", cli.SecretId)
sig := Signature(param, method, Uri, cli.SecretKey)
param.Set("Signature", sig)
req, err := http.NewRequest(method, "https://"+Uri+"?"+param.Encode(), body)
if err != nil {
return fmt.Errorf("构建请求错误: %s", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("执行请求错误: %s", err)
}
defer resp.Body.Close()
w, ok := respInfo.(*bytes.Buffer)
if ok {
io.Copy(w, resp.Body)
return nil
}
info, ok := respInfo.(Responser)
if !ok {
return fmt.Errorf("不可识别的响应结构参数")
}
err = json.NewDecoder(resp.Body).Decode(info)
if err != nil {
return fmt.Errorf("读取响应错误: %s", err)
}
return info.Error()
}