代码:
func HttpBuildQuery(params map[string]string) (param_str string) {
params_arr := make([]string, 0, len(params))
for k, v := range params {
params_arr = append(params_arr, fmt.Sprintf("%s=%s", k, v))
}
//fmt.Println(params_arr)
param_str = strings.Join(params_arr, "&")
return param_str
}
func main(){
params := map[string]string{
"action": "getAccessToken",
"client_code": "aaaaa",
"client_secret": "ccccc",
"interface": "wxapi",
"time": strconv.FormatInt(time.Now().Unix(), 10),
}
param_str := HttpBuildQuery(params)
}
golang 标准做法1:
import (
"fmt"
"net/url"
)
func main() {
q := url.Values{}
q.Set("action", "getAccessToken")
q.Set("client_code", clientCode)
q.Set("client_secret", clientSecret)
q.Set("interface", "wxapi")
q.Set("refresh", refresh)
q.Set("time", strconv.FormatInt(time.Now().Unix(), 10))
fmt.Printf(q.Encode())
//此方法对中文不友好
}
golang 标准做法2:
import (
"fmt"
"net/url"
)
func main() {
var uri url.URL
q := uri.Query()
q.Add("name", "张三")
q.Add("age", "20")
q.Add("sex", "1")
queryStr := q.Encode()
fmt.Println(queryStr)
}
//此方法会中文友好,且会把key按照字母 a-z 排序。
有疑问加站长微信联系(非本文作者)