From adba45da11cee96509afe017c1368470394eeb78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E6=B6=9B?= Date: Wed, 12 Jul 2023 11:10:14 +0800 Subject: [PATCH] =?UTF-8?q?feat(serialize):=E5=9F=BA=E6=9C=AC=E5=AE=8C?= =?UTF-8?q?=E6=88=90Hex=E5=92=8CBase64=E7=9A=84=E7=BC=96=E8=A7=A3=E7=A0=81?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- serialize/base64/base64.go | 24 ++++++++++++++++++++++++ serialize/hex/hex.go | 26 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 serialize/base64/base64.go create mode 100644 serialize/hex/hex.go diff --git a/serialize/base64/base64.go b/serialize/base64/base64.go new file mode 100644 index 0000000..c77d9be --- /dev/null +++ b/serialize/base64/base64.go @@ -0,0 +1,24 @@ +// 提供base64编码解码功能。 +package base64 + +import "encoding/base64" + +// 采用标准Base64编码方式将字节数组转换为字符串。 +func ToBase64(b []byte) string { + return base64.StdEncoding.EncodeToString(b) +} + +// 采用URL Encoding Base64编码方式将字节数组转换为字符串。 +func ToBase64URLEncoded(b []byte) string { + return base64.URLEncoding.EncodeToString(b) +} + +// 采用标准Base64编码方式讲字符串转换为字节数组。 +func FromBase64(s string) ([]byte, error) { + return base64.StdEncoding.DecodeString(s) +} + +// 采用URL Encoding Base64编码方式讲字符串转换为字节数组。 +func FromBase64URLEncoded(s string) ([]byte, error) { + return base64.URLEncoding.DecodeString(s) +} diff --git a/serialize/hex/hex.go b/serialize/hex/hex.go new file mode 100644 index 0000000..a20ac09 --- /dev/null +++ b/serialize/hex/hex.go @@ -0,0 +1,26 @@ +// 提供字节数组到十六进制字符串的快捷转换 +package hex + +import "encoding/hex" + +type HexSerializeError struct { + source *error +} + +func (e *HexSerializeError) Error() string { + return "无法将字节数组转换为十六进制字符串。" +} + +// 将给定的字节数组转换为十六进制字符串。 +func ToHex(b []byte) string { + return hex.EncodeToString(b) +} + +// 将给定的十六进制字符串转换为字节数组。如果不能成功完成转换将返回错误和一个空字节数组。 +func FromHex(s string) ([]byte, error) { + b, err := hex.DecodeString(s) + if err != nil { + return make([]byte, 0), &HexSerializeError{source: &err} + } + return b, nil +}