go使用base64编码

Go中的系统库中提供了encoding/base64编码/解码的内置支持.

encoding/base64提供了四种模式的编码/解码

  • StdEncoding:常规编码
  • URLEncoding:URL safe 编码
  • RawStdEncoding:常规编码,末尾不补 =
  • RawURLEncoding:URL safe 编码,末尾不补 =

其中,URL safe 编码,相当于是替换掉字符串中的特殊字符,+ 和 /。

各种模式的编码/解码测试用例如下:

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    msg := []byte("Hello world. 你好,世界!")

    encoded := base64.StdEncoding.EncodeToString(msg)
    fmt.Println(encoded)
    // SGVsbG8gd29ybGQuIOS9oOWlve+8jOS4lueVjO+8gQ==

    decoded, _ := base64.StdEncoding.DecodeString(encoded)
    fmt.Println(string(decoded))
    // Hello world. 你好,世界!

    encoded = base64.RawStdEncoding.EncodeToString(msg)
    fmt.Println(encoded)
    // SGVsbG8gd29ybGQuIOS9oOWlve+8jOS4lueVjO+8gQ

    decoded, _ = base64.RawStdEncoding.DecodeString(encoded)
    fmt.Println(string(decoded))
    // Hello world. 你好,世界!

    encoded = base64.URLEncoding.EncodeToString(msg)
    fmt.Println(encoded)
    // SGVsbG8gd29ybGQuIOS9oOWlve-8jOS4lueVjO-8gQ==

    decoded, _ = base64.URLEncoding.DecodeString(encoded)
    fmt.Println(string(decoded))
    // Hello world. 你好,世界!

    encoded = base64.RawURLEncoding.EncodeToString(msg)
    fmt.Println(encoded)
    // SGVsbG8gd29ybGQuIOS9oOWlve-8jOS4lueVjO-8gQ

    decoded, _ = base64.RawURLEncoding.DecodeString(encoded)
    fmt.Println(string(decoded))
    // Hello world. 你好,世界!
}

本文参考:https://syaning.github.io/go-pkgs/encoding/base64.html

0%