Go提供對(duì)base64編碼/解碼的內(nèi)置支持。導(dǎo)入帶有b64名稱的encoding/base64軟件包,而不是默認(rèn)的base64。它會(huì)節(jié)省我們一些空間。Go支持標(biāo)準(zhǔn)和URL兼容的base64。 以下是使用標(biāo)準(zhǔn)編碼器進(jìn)行編碼的方法。編碼器需要一個(gè)[]byte,所以將字符串轉(zhuǎn)換為該類型。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.com/go/go_environment.html
base64-encoding.go的完整代碼如下所示 -
package main
// This syntax imports the `encoding/base64` package with
// the `b64` name instead of the default `base64`. It'll
// save us some space below.
import b64 "encoding/base64"
import "fmt"
func main() {
// Here's the `string` we'll encode/decode.
data := "abc123!?$*&()'-=@~"
// Go supports both standard and URL-compatible
// base64. Here's how to encode using the standard
// encoder. The encoder requires a `[]byte` so we
// cast our `string` to that type.
sEnc := b64.StdEncoding.EncodeToString([]byte(data))
fmt.Println(sEnc)
// Decoding may return an error, which you can check
// if you don't already know the input to be
// well-formed.
sDec, _ := b64.StdEncoding.DecodeString(sEnc)
fmt.Println(string(sDec))
fmt.Println()
// This encodes/decodes using a URL-compatible base64
// format.
uEnc := b64.URLEncoding.EncodeToString([]byte(data))
fmt.Println(uEnc)
uDec, _ := b64.URLEncoding.DecodeString(uEnc)
fmt.Println(string(uDec))
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run base64-encoding.go
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~