go的encoding/base64有四种编码方式:
编码方式 | 说明 |
---|---|
StdEncoding | 常规编码 |
URLEncoding | URL safe 编码,相当于替换掉字符串中的特殊字符,+ 和 / |
RawStdEncoding | 常规编码,末尾不补 = |
RawURLEncoding | 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. 你好,世界!
// URL safe 编码
encoded = base64.URLEncoding.EncodeToString(msg)
fmt.Println(encoded)
// SGVsbG8gd29ybGQuIOS9oOWlve-8jOS4lueVjO-8gQ==
decoded, _ = base64.URLEncoding.DecodeString(encoded)
fmt.Println(string(decoded))
// Hello world. 你好,世界!
// URL safe 编码,末尾不补 =
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
https://www.rfc-editor.org/rfc/rfc4648
http://doc.golang.ltd/pkg/encoding_base64.htm
https://base64.us/
到此这篇关于go实现base64编码的四种方式的文章就介绍到这了,更多相关go实现base64编码内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!