netease.go
1.8 KB
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
package im
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
var DefaultImClient Client
var ErrorFailCall = fmt.Errorf(" imclient call failed")
func InitImClient(baseUrl, appKey, appSecret string) {
DefaultImClient = Client{
baseUrl: baseUrl,
appKey: appKey,
appSecret: appSecret,
}
}
type Client struct {
baseUrl string
appKey string
appSecret string
}
func (i Client) Call(param RequestParam) ([]byte, error) {
return i.httpDo(param.GetPath(), param.Format())
}
func (i Client) buildHeader() http.Header {
var h = http.Header{}
curTime := strconv.FormatInt(time.Now().Unix(), 10)
nonce := strconv.FormatInt(time.Now().Unix()+rand.Int63n(5000), 10)
checkSum := buildCheckSum(i.appSecret, nonce, curTime)
h.Set("Content-Type", "application/x-www-form-urlencoded")
h.Set("AppKey", i.appKey)
h.Set("Nonce", nonce)
h.Set("CurTime", curTime)
h.Set("CheckSum", checkSum)
return h
}
func (i Client) httpDo(path string, posts map[string]string) ([]byte, error) {
client := http.Client{
Timeout: 5 * time.Second, //请求超时时间5秒
}
reqURL := i.baseUrl + path
params := url.Values{}
for k, v := range posts {
params.Add(k, v)
}
req, err := http.NewRequest("POST", reqURL, strings.NewReader(params.Encode()))
if err != nil {
return nil, err
}
req.Header = i.buildHeader()
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
func buildCheckSum(appSecret string, nonce string, curTime string) string {
str := []byte(appSecret + nonce + curTime)
sh := sha1.New()
sh.Write(str)
result := hex.EncodeToString(sh.Sum(nil))
return strings.ToLower(result)
}