Golang Url Encode Decode


原文链接: Golang Url Encode Decode

golang中使用url encoding遇到的小坑

https://stackoverflow.com/questions/13820280/encode-decode-urls

Example: Turns "My String" to "My%20String"

package urlencode
import "net/url"
// UrlEncoded encodes a string like Javascript's encodeURIComponent()
func UrlEncoded(str string) (string, error) {
	u, err := url.Parse(str)
	if err != nil {
		return "", err
	}
	return u.String(), nil
}

Go语言的net/url包中实现了类似java URLEncoder和URLDecoder的函数,它们是
QueryEscape:类似URLEncoder
QueryUnescape:类似URLDecoder
使用例子如下:
首先要引入net/url包

import (
"fmt"
"net/url"
)
urltest := "http://www.baidu.com/s?wd=自由度"
fmt.Println(urltest)
encodeurl:= url.QueryEscape(urltest)
fmt.Println(encodeurl)
decodeurl,err := url.QueryUnescape(encodeurl)
if err != nil {
fmt.Println(err)
}
fmt.Println(decodeurl)

输出结果:

http://www.baidu.com/s?wd=自由度
http%3A%2F%2Fwww.baidu.com%2Fs%3Fwd%3D%E8%87%AA%E7%94%B1%E5%BA%A6
http://www.baidu.com/s?wd=自由度
`