util/base64.go

60 lines
1.1 KiB
Go
Raw Permalink Normal View History

2024-01-19 10:41:09 +08:00
package util
import (
2024-01-23 23:02:08 +08:00
"encoding/base64"
2024-01-19 10:41:09 +08:00
)
type Base64Result struct {
2024-01-23 23:02:08 +08:00
result string
err error
2024-01-19 10:41:09 +08:00
}
func (b *Base64Result) Bytes() []byte {
2024-02-19 16:46:42 +08:00
if b.err != nil {
return []byte{}
}
2024-01-23 23:02:08 +08:00
return []byte(b.result)
2024-01-19 10:41:09 +08:00
}
func (b *Base64Result) String() string {
2024-02-19 16:46:42 +08:00
if b.err != nil {
return ""
}
2024-01-23 23:02:08 +08:00
return b.result
2024-01-19 10:41:09 +08:00
}
func (b *Base64Result) Error() error {
2024-01-23 23:02:08 +08:00
return b.err
2024-01-19 10:41:09 +08:00
}
func NewBase64Result(result string, err error) *Base64Result {
2024-01-23 23:02:08 +08:00
return &Base64Result{
result: result,
err: err,
}
2024-01-19 10:41:09 +08:00
}
type Base64 struct{}
func NewBase64() *Base64 {
2024-01-23 23:02:08 +08:00
return &Base64{}
2024-01-19 10:41:09 +08:00
}
func (b *Base64) EncodeBytes(data []byte) *Base64Result {
2024-01-23 23:02:08 +08:00
return NewBase64Result(base64.StdEncoding.EncodeToString(data), nil)
2024-01-19 10:41:09 +08:00
}
func (b *Base64) EncodeString(str string) *Base64Result {
2024-01-23 23:02:08 +08:00
return NewBase64Result(base64.StdEncoding.EncodeToString([]byte(str)), nil)
2024-01-19 10:41:09 +08:00
}
func (b *Base64) DecodeBytes(data []byte) *Base64Result {
2024-01-23 23:02:08 +08:00
res, err := base64.StdEncoding.DecodeString(string(data))
return NewBase64Result(string(res), err)
2024-01-19 10:41:09 +08:00
}
func (b *Base64) DecodeString(str string) *Base64Result {
2024-01-23 23:02:08 +08:00
res, err := base64.StdEncoding.DecodeString(str)
return NewBase64Result(string(res), err)
2024-01-19 10:41:09 +08:00
}