|
- package comm
-
- import (
- "bytes"
- "crypto/hmac"
- "crypto/md5"
- "encoding/hex"
- "encoding/json"
- "sort"
- "strings"
- )
-
- func Ksort(params map[string]interface{}) []string {
- keys := make([]string, len(params))
- i := 0
- for k, _ := range params {
- keys[i] = k
- i++
- }
- sort.Strings(keys)
- return keys
- }
- func KsortToStr(params map[string]string) []string {
- keys := make([]string, len(params))
- i := 0
- for k, _ := range params {
- keys[i] = k
- i++
- }
- sort.Strings(keys)
- return keys
- }
- func KsortToStrInterface(params map[string]interface{}) []string {
- keys := make([]string, len(params))
- i := 0
- for k, _ := range params {
- keys[i] = k
- i++
- }
- sort.Strings(keys)
- return keys
- }
-
- // Marshal 序列化参数
- func GetSortJson(o interface{}) string {
- // 序列化一次
- raw, _ := json.Marshal(o)
-
- // 反序列化为map
- m := make(map[string]interface{})
- reader := bytes.NewReader(raw)
- decode := json.NewDecoder(reader)
- decode.UseNumber()
- _ = decode.Decode(&m)
-
- // 重新做一次序列化,并禁用Html Escape
- buffer := bytes.NewBufferString("")
- encoder := json.NewEncoder(buffer)
- encoder.SetEscapeHTML(false)
- _ = encoder.Encode(m)
-
- marshal := strings.TrimSpace(buffer.String()) // Trim掉末尾的换行符
- return marshal
- }
- func HmacMd5(key, data string) string {
- h := hmac.New(md5.New, []byte(key))
- h.Write([]byte(data))
- return strings.ToUpper(hex.EncodeToString(h.Sum([]byte(""))))
- }
|