菜鸟笔记
提升您的技术认知

GO 语言URL encode与decode方法

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=%E6%9C%89%E6%B2%A1%E6%9C%89%E4%BA%BA
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
}