Files
gf/encoding/gbase64/gbase64.go

68 lines
1.9 KiB
Go

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// 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.
// Package gbase64 provides useful API for BASE64 encoding/decoding algorithm.
package gbase64
import (
"encoding/base64"
"github.com/gogf/gf/util/gconv"
"io/ioutil"
)
// 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
}
// Decode decodes bytes with BASE64 algorithm.
func Decode(dst []byte) ([]byte, error) {
src := make([]byte, base64.StdEncoding.DecodedLen(len(dst)))
n, err := base64.StdEncoding.Decode(src, dst)
return src[:n], err
}
// 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))
}
// EncryptFile encodes file content of <path> using BASE64 algorithms.
func EncodeFile(path string) ([]byte, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return Encode(content), nil
}
// EncodeFileToString encodes file content of <path> to string using BASE64 algorithms.
func EncodeFileToString(path string) (string, error) {
content, err := EncodeFile(path)
if err != nil {
return "", err
}
return gconv.UnsafeBytesToStr(content), nil
}
// DecodeString decodes string with BASE64 algorithm.
func DecodeString(str string) ([]byte, error) {
return Decode([]byte(str))
}
// DecodeString decodes string with BASE64 algorithm.
func DecodeToString(str string) (string, error) {
b, err := DecodeString(str)
return gconv.UnsafeBytesToStr(b), err
}