要解码一个Base64编码的字符串,请使用 DecodeString()函数,从 encoding/base64标准库包中的函数。这个函数接收一个已编码的字符串作为参数,并返回一个字节片,以及解码错误。为了得到解码后的字符串,将字节片转换为字符串。
package main
import (
"encoding/base64"
"fmt"
)
func main() {
rawDecodedText, err := base64.StdEncoding.DecodeString("aGVsbG8gZnJvbSBnb3NhbXBsZXMuZGV2IGJhc2U2NCBlbmNvZGluZyBleGFtcGxlIQ==")
if err != nil {
panic(err)
}
fmt.Printf("Decoded text: %s\n", rawDecodedText)
}
输出
Decoded text: hello from gosamples.dev base64 encoding example!
StdEncoding 是一个代表标准 base64 编码的对象,如RFC 4648 所定义,而 DecodeString()是它的方法。