我们可以在Go中编码String和url。 Go有带字节数组并转换为字符串编码的Encoder。
解码器获取编码后的值并将其转换为原始字符串。
Go Base64示例
package main
import "fmt"
import b64 "encoding/base64"
func main() {
data := "srcmini@12345!@#$%^&*()"
strEncode :=b64.StdEncoding.EncodeToString([]byte(data))
fmt.Println("value to be encode "+data)
fmt.Println("Encoden value: "+strEncode)
fmt.Println()
fmt.Print("Value to be decode "+strEncode)
strDecode, _ := b64.StdEncoding.DecodeString(strEncode)
fmt.Println("Decoded value "+string( strDecode))
fmt.Println()
url := "https://golang.org/ref/spec"
fmt.Println("url to be encode "+url)
urlEncode := b64.URLEncoding.EncodeToString([]byte(url))
fmt.Println("Encoded url "+urlEncode)
fmt.Println("value to be decode "+urlEncode)
strDecode2, _ := b64.URLEncoding.DecodeString(urlEncode)
fmt.Println("Decoded value "+string(strDecode2))
}
输出:
value to be encode srcmini@12345!@#$%^&*()
Encoden value: SmF2YVRwb2ludEAxMjM0NSFAIyQlXiYqKCk=
Value to be decode SmF2YVRwb2ludEAxMjM0NSFAIyQlXiYqKCk=Decoded value Ja-vaTpoint@12345!@#$%^&*()
url to be encode https://golang.org/ref/spec
Encoded url aHR0cHM6Ly9nb2xhbmcub3JnL3JlZi9zcGVj
value to be decode aHR0cHM6Ly9nb2xhbmcub3JnL3JlZi9zcGVj
Decoded value https://golang.org/ref/spec
Process finished with exit code 0