chat-backend/utils/helper.go

93 lines
1.7 KiB
Go

package utils
import (
"crypto/md5"
"fmt"
"reflect"
"sort"
"strings"
)
// GetAddress
// 获取监听地址
//
// @return []string
func GetListenAddress() []string {
address := Conf.Get("init", "addr")
addressArr := strings.Split(address, "://")
if addressArr[0] == "https" {
return []string{addressArr[0], addressArr[1]}
}
var addr string
if len(addressArr) > 1 {
addr = addressArr[1]
} else {
addr = addressArr[0]
}
return []string{"http", addr}
}
// GetProxy
// 获取代理服务器
//
// @return string
func GetProxyServer() string {
proxy := Conf.Get("proxy", "addr")
if proxy == "" {
return ""
}
proxyArr := strings.Split(proxy, "://")
if proxyArr[0] != "http" && proxyArr[0] != "https" {
return "http://" + proxyArr[0]
}
return proxy
}
// Md5
//
// @param text
// @return string
func Md5(text string) string {
hash := md5.New()
hash.Write([]byte(text))
byteData := hash.Sum(nil)
return fmt.Sprintf("%x", byteData)
}
// MakeSign
// 生成签名
//
// @param obj
// @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)
}
//进行键排序
keys := make([]string, len(signmap))
j := 0
for k := range signmap {
keys[j] = k
j++
}
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)
}
}
return Md5(str + "key=" + privateKey)
}