Golang base64 编码示例
Golang 提供对 base64 编码/解码的内置支持。 直接在标准库中我们有“encoding/base64
”,所以不需要下载或安装第三方库。 我们来看看 Go 的 base64 编码文档 https://golang.org/pkg/encoding/base64/
。 为了将字符串编码或解码为 base64,我们需要使用提供以下方法的 Encoder 类型
func (enc *Encoding) DecodeString(s string) ([]byte, error)
并将字符串(在本例中为字节片段)编码为 base64 格式
func (enc *Encoding) EncodeToString(src []byte) string
标准库还为我们提供了对字节片进行解码和编码的方法,以用于更通用的用途(解码、编码)。
这是一个关于如何编码和解码 base64 字符串的示例
package main
import (
"encoding/base64"
"fmt"
)
func main() {
// Here's the `string` we'll encode
plainStr := "Hello World."
// The encoder we will use is the base64.StdEncoding
// It requires a byte slice so we cast the string to []byte
encodedStr := base64.StdEncoding.EncodeToString([]byte(plainStr))
fmt.Println(encodedStr)
// Decoding may return an error, in case the input is not well formed
decodedStrAsByteSlice, err := base64.StdEncoding.DecodeString(encodedStr)
if err != nil {
panic("malformed input")
}
fmt.Println(string(decodedStrAsByteSlice))
}
下面是预期的输出
SGVsbG8gV29ybGQu
Hello World.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。