一、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
