gf/encoding/gbase64/gbase64.go

49 lines
1.4 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
2017-12-29 16:03:30 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2017-12-29 16:03:30 +08:00
2019-07-02 16:56:10 +08:00
// Package gbase64 provides useful API for BASE64 encoding/decoding algorithm.
2017-11-23 10:21:28 +08:00
package gbase64
import (
2019-06-19 09:06:52 +08:00
"encoding/base64"
"github.com/gogf/gf/util/gconv"
2017-11-23 10:21:28 +08:00
)
2019-07-02 16:56:10 +08:00
// Encode encodes bytes with BASE64 algorithm.
func Encode(src []byte) []byte {
dst := make([]byte, base64.StdEncoding.EncodedLen(len(src)))
base64.StdEncoding.Encode(dst, src)
return dst
2017-11-23 10:21:28 +08:00
}
2019-07-02 16:56:10 +08:00
// Decode decodes bytes with BASE64 algorithm.
func Decode(dst []byte) ([]byte, error) {
src := make([]byte, base64.StdEncoding.DecodedLen(len(dst)))
2019-07-02 17:30:18 +08:00
n, err := base64.StdEncoding.Decode(src, dst)
2019-07-09 08:07:50 +08:00
return src[:n], err
2019-07-02 16:56:10 +08:00
}
// EncodeString encodes string with BASE64 algorithm.
func EncodeString(src string) string {
return EncodeToString([]byte(src))
}
// EncodeToString encodes bytes to string with BASE64 algorithm.
func EncodeToString(src []byte) string {
return gconv.UnsafeBytesToStr(Encode(src))
2019-07-02 16:56:10 +08:00
}
// DecodeString decodes string with BASE64 algorithm.
func DecodeString(str string) ([]byte, error) {
return Decode([]byte(str))
2019-06-19 09:06:52 +08:00
}
// DecodeString decodes string with BASE64 algorithm.
func DecodeToString(str string) (string, error) {
b, err := DecodeString(str)
return gconv.UnsafeBytesToStr(b), err
}