优化签名生成函数

This commit is contained in:
TOP糯米 2023-03-27 21:41:47 +08:00
parent bc8c7d1e12
commit 9000c53f0e
1 changed files with 11 additions and 19 deletions

View File

@ -62,30 +62,22 @@ func Md5(text string) string {
// @param privateKey
// @return string
func MakeSign(obj interface{}, privateKey string) string {
signmap := map[string]interface{}{}
valueOfObj := reflect.ValueOf(obj)
for i := 0; i < valueOfObj.NumField(); i++ {
signmap[valueOfObj.Type().Field(i).Name] = valueOfObj.Field(i)
}
keysCount := valueOfObj.NumField()
//进行键排序
keys := make([]string, len(signmap))
j := 0
for k := range signmap {
keys[j] = k
j++
keys := make([]string, keysCount)
for i := 0; i < keysCount; i++ {
keys[i] = valueOfObj.Type().Field(i).Name
}
sort.Strings(keys)
//获取 value 值,拼接成一行
str := ""
for _, k := range keys {
if strings.ToLower(k) == "sign" {
continue
}
if v, ok := signmap[k]; ok {
str = fmt.Sprintf("%s%s=%v&", str, strings.ToLower(k), v)
}
currentKey := ""
var currentValue reflect.Value
for j := 0; j < keysCount; j++ {
currentKey = strings.ToLower(keys[j])
currentValue = valueOfObj.FieldByName(keys[j])
str = fmt.Sprintf("%s%s=%v&", str, currentKey, currentValue)
}
return Md5(str + "key=" + privateKey)