github.com/872409/go-netease-im@v1.0.2-0.20201109080841-fdb3e13691c5/client.go (about)

     1  package netease
     2  
     3  import (
     4  	"encoding/json"
     5  	// "fmt"
     6  
     7  	// "encoding/json"
     8  	"errors"
     9  	"strconv"
    10  	"sync"
    11  	"time"
    12  
    13  	"github.com/go-resty/resty"
    14  	jsoniter "github.com/json-iterator/go"
    15  )
    16  
    17  var jsonTool = jsoniter.ConfigCompatibleWithStandardLibrary
    18  
    19  // ImClient .
    20  type ImClient struct {
    21  	AppKey    string
    22  	AppSecret string
    23  	Nonce     string
    24  
    25  	mutex  *sync.Mutex
    26  	client *resty.Client
    27  }
    28  
    29  // CreateImClient  创建im客户端,proxy留空表示不使用代理
    30  func CreateImClient(appKey, appSecret, httpProxy string) *ImClient {
    31  	c := &ImClient{AppKey: appKey, AppSecret: appSecret, Nonce: RandStringBytesMaskImprSrc(64), mutex: new(sync.Mutex)}
    32  	c.client = resty.New()
    33  	if len(httpProxy) > 0 {
    34  		c.client.SetProxy(httpProxy)
    35  	}
    36  
    37  	c.client.SetHeader("Accept", "application/json;charset=utf-8")
    38  	c.client.SetHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8;")
    39  	c.client.SetHeader("AppKey", c.AppKey)
    40  	c.client.SetHeader("Nonce", c.Nonce)
    41  
    42  	return c
    43  }
    44  
    45  func (c *ImClient) setCommonHead(req *resty.Request) {
    46  	c.mutex.Lock() // 多线程并发访问map导致panic
    47  	defer c.mutex.Unlock()
    48  
    49  	timeStamp := strconv.FormatInt(time.Now().Unix(), 10)
    50  	req.SetHeader("CurTime", timeStamp)
    51  	req.SetHeader("CheckSum", ShaHashToHexStringFromString(c.AppSecret+c.Nonce+timeStamp))
    52  }
    53  
    54  func (c *ImClient) post(url string, fromData map[string]string, jsonResultKey string) (info *json.RawMessage, err error) {
    55  	client := c.client.R()
    56  	c.setCommonHead(client)
    57  	client.SetFormData(fromData)
    58  
    59  	resp, err := client.Post(url)
    60  	info, err = handleResp(resp, err, jsonResultKey)
    61  	return
    62  }
    63  
    64  func handleResp(resp *resty.Response, respErr error, jsonResultKey string) (info *json.RawMessage, err error) {
    65  	if respErr != nil {
    66  		return nil, respErr
    67  	}
    68  
    69  	var jsonRes map[string]*json.RawMessage
    70  
    71  	err = jsoniter.Unmarshal(resp.Body(), &jsonRes)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  
    76  	var code int
    77  	err = json.Unmarshal(*jsonRes["code"], &code)
    78  	if err != nil {
    79  		return nil, err
    80  	}
    81  
    82  	if code != 200 {
    83  		var msg string
    84  		json.Unmarshal(*jsonRes["desc"], &msg)
    85  		return nil, errors.New(msg)
    86  	}
    87  
    88  	return jsonRes[jsonResultKey], nil
    89  }