netease.go 1.8 KB
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)
}