52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
package encode
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
)
|
|
|
|
const (
|
|
standardBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
|
customBase64 = "KLMPQRSTUVWXYZABCGHdefIJjkNOlmnopqrstuvwxyzabcghiDEF34501289+67/"
|
|
)
|
|
|
|
var base64Map = func() map[byte]byte {
|
|
m := make(map[byte]byte, len(standardBase64))
|
|
for i := 0; i < len(standardBase64); i++ {
|
|
m[standardBase64[i]] = customBase64[i]
|
|
}
|
|
return m
|
|
}()
|
|
|
|
// CustomBase64Encode 使用自定义字符映射对标准 Base64 进行转换
|
|
func CustomBase64Encode(data []byte) string {
|
|
standard := base64.StdEncoding.EncodeToString(data)
|
|
result := make([]byte, len(standard))
|
|
for i := 0; i < len(standard); i++ {
|
|
if c, ok := base64Map[standard[i]]; ok {
|
|
result[i] = c
|
|
} else {
|
|
result[i] = standard[i]
|
|
}
|
|
}
|
|
return string(result)
|
|
}
|
|
|
|
// EncodeJSON 将任意数据编码为 JSON 后,再进行自定义 Base64 编码
|
|
func EncodeJSON(v any) (string, error) {
|
|
jsonBytes, err := json.Marshal(v)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return CustomBase64Encode(jsonBytes), nil
|
|
}
|
|
|
|
// ParseBase64Param 解析 base64Resp 参数,默认为 true
|
|
func ParseBase64Param(c interface{ Query(string) string }) bool {
|
|
v := c.Query("base64Resp")
|
|
if v == "" || v == "true" || v == "1" {
|
|
return true
|
|
}
|
|
return false
|
|
}
|