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.