|
|
package im
|
|
|
|
|
|
import (
|
|
|
"crypto/sha1"
|
|
|
"encoding/hex"
|
|
|
"io/ioutil"
|
|
|
"math/rand"
|
|
|
"net/http"
|
|
|
"net/url"
|
|
|
"strconv"
|
|
|
"strings"
|
|
|
"time"
|
|
|
)
|
|
|
|
|
|
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)
|
|
|
}
|
|
|
|
|
|
type ImClient struct {
|
|
|
baseUrl string
|
|
|
appKey string
|
|
|
appSecret string
|
|
|
}
|
|
|
|
|
|
func (i ImClient) 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 ImClient) httpDo(path string, posts map[string]string) ([]byte, error) {
|
|
|
client := http.Client{}
|
|
|
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 (i ImClient) Call(param ImParam) ([]byte, error) {
|
|
|
return i.httpDo(param.GetPath(), param.Format())
|
|
|
} |
...
|
...
|
|