1. 程式人生 > >GO 語言URL encode與decode方法

GO 語言URL encode與decode方法

GO 筆記

- GO 語言http請求編碼

在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
}