Photo By: viktorhanacek
上一篇文章讲了Go语言的几种URL编码方法,这篇文章我们来讲一讲Go语言的URL解码方法。URL解码是编码的逆操作,可以将URL编码的字符转换成正常的形式
Go语言内置的net/url 包包含一个内置方法 QueryUnescape (QueryEscape编码方法的对应解码方法)可以解码一个字符串。下面是一个简单的例子
package main import ( "fmt" "net/url" ) func main() { encodedValue := "Hello+%E4%B8%AD%E5%9B%BD" decodedValue, err := url.QueryUnescape(encodeValue) if err := nil { fmt.Println(err) return } fmt.Println(decodedValue) }输出
Hello 中国“param1=value¶m2=value2”
可以使用url.ParseQuery() 方法将由&分隔的一系列 key=value 键值对解析为map[string] []string
package main import ( "fmt" "net/url" ) func main() { queryStr := "name=Rajeev%20Singh&phone=%2B9199999999&phone=%2B628888888888" params, err := url.ParseQuery(queryStr) if err != nil { fmt.Println(err) return } fmt.Println("Query Params: ") for key, value := range params { fmt.Printf(" %v = %v\n", key, value) } }输出
Query Params: name = [Rajeev Singh] phone = [+9199999999 +628888888888]PathUnescape() 函数和 QueryUnescape() 相似,只是它不对不会把 + 转换为空格,因为 + 允许出现在URL路径中
package main import ( "fmt" "net/url" ) func main() { path:= "path%20with%3Freserved+characters" unescapedPath, err := url.PathUnescape(path) if err != nil { fmt.Println(err) } fmt.Println(unescapedPath) }输出
path with?reserved+characters最后,我们来看一个解码完整URL的例子
package main import ( "fmt" "net/url" ) func main() { u, err := url.Parse("https://www.website.com/person?name=Rajeev%20Singh&phone=%2B919999999999&phone=%2B628888888888") if err != nil { fmt.Println(err) return } fmt.Println("Scheme: ", u.Scheme) fmt.Println("Host: ", u.Host) queries := u.Query() fmt.Println("Query Strings: ") for key, value := range queries { fmt.Printf(" %v = %v\n", key, value) } fmt.Println("Path: ", u.Path) }输出
Scheme: https Host: www.website.com Query Strings: phone = [+919999999999 +628888888888] name = [Rajeev Singh] Path: /person