Golang urlencode与urldecode编码解码
一、urlencode
golang下可以使用net/url模块实现urlencode和urldecode操作。具体实现的函数为url.QueryEscape和url.QueryUnescape,代码如下:
package main import( "fmt" "net/url" ) func main() { var urlStr string = "运维之路" escapeUrl := url.QueryEscape(urlStr) fmt.Println("编码:",escapeUrl) enEscapeUrl, _ := url.QueryUnescape(escapeUrl) fmt.Println("解码:",enEscapeUrl) }
如果涉及到多个参数转码的,这在get和post请求中都有,比如id=100&site=361way.com这样的。可以在通过url.Values进行增加后转码,发下:
package main import ( "fmt" "net/url" ) func main() { params := url.Values{} params.Add("name", "@Rajeev") params.Add("phone", "+919999999999") fmt.Println(params.Encode()) } #输出: name=%40Rajeev&phone=%2B919999999999
同样的,我们通过url的其他函数处理操作过后,一个典型的get请求的URL如下:
package main import ( "fmt" "net/url" ) func main() { // Let's start with a base url baseUrl, err := url.Parse("http://www.mywebsite.com") if err != nil { fmt.Println("Malformed URL: ", err.Error()) return } // Add a Path Segment (Path segment is automatically escaped) baseUrl.Path += "path with?reserved characters" // Prepare Query Parameters params := url.Values{} params.Add("q", "Hello World") params.Add("u", "@rajeev") // Add Query Parameters to the URL baseUrl.RawQuery = params.Encode() // Escape Query Parameters fmt.Printf("Encoded URL is %q\n", baseUrl.String()) } #输出结果 Encoded URL is "http://www.mywebsite.com/path%20with%3Freserved%20characters?q=Hello+World&u=%40rajeev"
二、urldecode
简单的url解码,直接使用Unescape就可以了,如下:
package main import ( "fmt" "log" "net/url" ) func main() { encodedValue := "Hell%C3%B6+W%C3%B6rld%40Golang" decodedValue, err := url.QueryUnescape(encodedValue) if err != nil { log.Fatal(err) return } fmt.Println(decodedValue) }
带form 参数,就像上面提到的"param1=value1¶m2=value2"这种格式的可以使用url.ParseQuery()参数解析成map[string][]string格式,如下:
package main import ( "fmt" "log" "net/url" ) func main() { queryStr := "name=Rajeev%20Singh&phone=%2B9199999999&phone=%2B628888888888" params, err := url.ParseQuery(queryStr) if err != nil { log.Fatal(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]
一个get请求类,后面带参数的URL,可以通过如下方式解析并解码
package main import ( "fmt" "log" "net/url" ) func main() { u, err := url.Parse("https://www.website.com/person?name=Rajeev%20Singh&phone=%2B919999999999&phone=%2B628888888888") if err != nil { log.Fatal(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
posted on 2021-06-10 16:44 running-fly 阅读(1754) 评论(0) 编辑 收藏 举报