chat-backend/core/data.go

88 lines
1.6 KiB
Go

package core
import (
"chatgpt/util"
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
)
// RequestData
type RequestData struct {
Words string `json:"words"`
Time int `json:"time"`
Sign string `json:"sign"`
}
// Response
// 响应体
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data string `json:"data"`
Sign string `json:"sign"`
}
// ResponseData
// 响应数据
type ResponseData map[string]interface{}
// BuildResponse
// 构建响应体
//
// @param privateKey
// @param code
// @param msg
// @param data
// @return string
func BuildResponse(privateKey string, code int, msg string, data ResponseData) string {
resp := Response{
Code: code,
Msg: msg,
}
dataJson, _ := json.Marshal(data)
resp.Data = util.Base64{
Content: []byte(dataJson),
}.Encode()
if privateKey != "" {
resp.Sign = MakeSign(resp, privateKey)
}
respJson, _ := json.Marshal(resp)
return string(respJson)
}
// MakeSign
// 生成签名
//
// @param obj
// @param privateKey
// @return string
func MakeSign(obj interface{}, privateKey string) string {
valueOfObj := reflect.ValueOf(obj)
keysCount := valueOfObj.NumField()
keys := make([]string, keysCount)
for i := 0; i < keysCount; i++ {
keys[i] = valueOfObj.Type().Field(i).Name
}
sort.Strings(keys)
str := ""
currentKey := ""
var currentValue reflect.Value
for j := 0; j < keysCount; j++ {
currentKey = strings.ToLower(keys[j])
if currentKey == "sign" {
continue
}
currentValue = valueOfObj.FieldByName(keys[j])
str = fmt.Sprintf("%s%s=%v&", str, currentKey, currentValue)
}
return util.Md5(str + "key=" + privateKey)
}