package main
import (
"fmt"
"crypto/md5"
"math/rand"
"sort"
"time"
)
type MapEntryHandler func (string, string)
// func printKeyValue(key string, value string) {
// fmt.Printf("key=%s, value=%s\n", key, value)
// }
// 按字母顺序遍历map
func traverseMapInStringOrder(params map[string]string, handler MapEntryHandler) {
keys := make([]string, 0)
for k, _ := range(params) {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
handler(k, params[k])
}
}
func main() {
params := map[string]string{}
params["captchaId"] = "d094d0ba1af"
params["validate"] = "17faa76f4a"
params["user"] = "mingzhanghui"
params["version"] = "1.0"
params["timestamp"] = "1553435624624"
rand.Seed(time.Now().UnixNano())
params["nounce"] = fmt.Sprintf("%d", rand.Int())
buff := []byte("gmy12345")
params["signature"] = fmt.Sprintf("%x", md5.Sum(buff))
// traverseMapInStringOrder(params, printKeyValue)
traverseMapInStringOrder(params, func (key string, value string) {
fmt.Printf("keys=%s, value=%s\n", key, value)
})
}
运行结果
keys=captchaId, value=d094d0ba1af
keys=nounce, value=5479916053492602771
keys=signature, value=be1776a32cea72e361e72d082252de93
keys=timestamp, value=1553435624624
keys=user, value=mingzhanghui
keys=validate, value=17faa76f4a