go 语言url encode与decode方法
在go中将url.values 类型进行url encode使用函数url.values.encode()
url decode 使用 url.parsequery(string)
package main
import (
"fmt"
"net/url"
)
func main() {
// url encode
v := url.values{
}
v.add("a", "aa")
v.add("b", "bb")
v.add("c", "有没有人")
body := v.encode()
fmt.println(v)
fmt.println(body)
// url decode
m, _ := url.parsequery(body)
fmt.println(m)
}
``
map[a:[aa] b:[bb] c:[有没有人]]
a=aa&b=bb&c=有没有人
map[b:[bb] c:[有没有人] a:[aa]]
// encode encodes the values into ``url encoded'' form
// ("bar=baz&foo=quux") sorted by key.
// 以url encoded方式编码values并按key进行排序
func (v values) encode() string {
if v == nil {
return ""
}
var buf bytes.buffer
keys := make([]string, 0, len(v))
for k := range v {
keys = append(keys, k)
}
sort.strings(keys)
for _, k := range keys {
vs := v[k]
prefix := queryescape(k) "="
for _, v := range vs {
if buf.len() > 0 {
buf.writebyte('&')
}
buf.writestring(prefix)
buf.writestring(queryescape(v))
}
}
return buf.string()
}
// parsequery parses the url-encoded query string and returns
// a map listing the values specified for each key.
// parsequery always returns a non-nil map containing all the
// valid query parameters found; err describes the first decoding error
// encountered, if any.
//
// query is expected to be a list of key=value settings separated by
// ampersands or semicolons. a setting without an equals sign is
// interpreted as a key set to an empty value.
// 解析url-encoded编码的字符串,按照key=value方式解析并构造map,没有=号的解析为key并设置值为空
func parsequery(query string) (values, error) {
m := make(values)
err := parsequery(m, query)
return m, err
}