Files
hospital-admin-api/extend/tencentIm/base.go
T

96 lines
2.1 KiB
Go

package tencentIm
import (
"bytes"
"encoding/json"
"errors"
"hospital-admin-api/config"
"io"
"math/rand"
"net/http"
"net/url"
"strconv"
"time"
)
// 请求返回值
type responseData struct {
ActionStatus string `json:"actionStatus"` // 请求处理的结果,“OK” 表示处理成功,“FAIL” 表示失败
ErrorCode int `json:"errorCode"` // 错误码,0表示成功,非0表示失败
ErrorInfo string `json:"errorInfo"` // 详细错误信息
}
// GetUserSign 获取签名
func GetUserSign(userId string) (string, error) {
if userId == "" {
userId = "administrator"
}
ImAppID := config.C.Im.ImAppID
ImSecret := config.C.Im.ImSecret
sign, err := GenUserSig(ImAppID, ImSecret, userId, 86400*180)
if err != nil || sign == "" {
return "", errors.New("签名获取失败")
}
return sign, err
}
// 获取请求链接
func getRequestUrlParams(userId string) (bool, string) {
// 获取签名
// 获取签名
sign, err := GetUserSign(userId)
if err != nil {
return false, err.Error()
}
rand.Seed(time.Now().UnixNano())
params := url.Values{}
params.Set("sdkappid", strconv.Itoa(config.C.Im.ImAppID))
params.Set("identifier", "administrator")
params.Set("usersig", sign)
params.Set("random", strconv.Itoa(rand.Intn(4294967296)))
params.Set("contenttype", "json")
queryString := params.Encode()
return true, queryString
}
// 统一请求
func postRequest(url string, requestBody []byte) (*responseData, error) {
var responseData responseData
// 发起 POST 请求
resp, err := http.Post(url, "application/json", bytes.NewBuffer(requestBody))
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &responseData)
if err != nil {
// json解析失败
return nil, err
}
if responseData.ErrorCode != 0 {
if responseData.ErrorInfo != "" {
return nil, errors.New(responseData.ErrorInfo)
} else {
return nil, errors.New("请求im失败")
}
}
return &responseData, nil
}