package utils import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "fmt" "regexp" "sort" "strconv" "strings" ) // HmacSha256 计算HmacSha256 // key 是加密所使用的key // data 是加密的内容 func HmacSha256(key string, data string) []byte { mac := hmac.New(sha256.New, []byte(key)) _, _ = mac.Write([]byte(data)) return mac.Sum(nil) } // 数据没有记录 func ErrNoRow() string { return " no row found" } // HmacSha256ToBase64 将加密后的二进制转Base64字符串 func HmacSha256ToBase64(key string, data string) string { return base64.URLEncoding.EncodeToString(HmacSha256(key, data)) } func GetSign(nonce, timestamp, appId, secret string) (sign string) { signStrMap := map[string]string{ "nonce": nonce, "timestamp": timestamp, "appid": appId, } keys := make([]string, 0, len(signStrMap)) for k := range signStrMap { keys = append(keys, k) } sort.Strings(keys) var signStr string for _, k := range keys { signStr += k + "=" + signStrMap[k] + "&" } signStr = strings.Trim(signStr, "&") fmt.Println("signStr:" + signStr) sign = HmacSha256ToBase64(secret, signStr) return } func StringsToJSON(str string) string { rs := []rune(str) jsons := "" for _, r := range rs { rint := int(r) if rint < 128 { jsons += string(r) } else { jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json } } return jsons } func StartIndex(page, pagesize int) int { if page > 1 { return (page - 1) * pagesize } return 0 } // TrimHtml func TrimHtml(src string) string { //将HTML标签全转换成小写 re, _ := regexp.Compile("\\<[\\S\\s]+?\\>") src = re.ReplaceAllStringFunc(src, strings.ToLower) re, _ = regexp.Compile("\\") src = re.ReplaceAllString(src, "") re, _ = regexp.Compile("class[\\S\\s]+?>") src = re.ReplaceAllString(src, "") re, _ = regexp.Compile("\\<[\\S\\s]+?\\>") src = re.ReplaceAllString(src, "") return strings.TrimSpace(src) } func Unique[T comparable](slice []T) []T { seen := make(map[T]struct{}) var unique []T for _, v := range slice { if _, exists := seen[v]; !exists { unique = append(unique, v) seen[v] = struct{}{} } } return unique } func GetOrmReplaceHolder(num int) string { var stringBuffer strings.Builder for i := 0; i < num; i++ { stringBuffer.WriteString("?") if i != num-1 { stringBuffer.WriteString(",") } } return stringBuffer.String() }