From cfebdf04a243ddc6af293d4b7a05ca09d5df7d5a Mon Sep 17 00:00:00 2001 From: gVisor bot Date: Fri, 19 Aug 2022 19:46:50 +0800 Subject: [PATCH] chore: Clean converter code and add doc --- common/convert/base64.go | 45 +++++++++++++++++++++++++++++++++++++ common/convert/converter.go | 30 ------------------------- 2 files changed, 45 insertions(+), 30 deletions(-) create mode 100644 common/convert/base64.go diff --git a/common/convert/base64.go b/common/convert/base64.go new file mode 100644 index 00000000..21d818f3 --- /dev/null +++ b/common/convert/base64.go @@ -0,0 +1,45 @@ +package convert + +import ( + "encoding/base64" + "strings" +) + +var ( + encRaw = base64.RawStdEncoding + enc = base64.StdEncoding +) + +// DecodeBase64 try to decode content from the given bytes, +// which can be in base64.RawStdEncoding, base64.StdEncoding or just plaintext. +func DecodeBase64(buf []byte) []byte { + result, err := tryDecodeBase64(buf) + if err != nil { + return buf + } + return result +} + +func tryDecodeBase64(buf []byte) ([]byte, error) { + dBuf := make([]byte, encRaw.DecodedLen(len(buf))) + n, err := encRaw.Decode(dBuf, buf) + if err != nil { + n, err = enc.Decode(dBuf, buf) + if err != nil { + return nil, err + } + } + return dBuf[:n], nil +} + +func urlSafe(data string) string { + return strings.NewReplacer("+", "-", "/", "_").Replace(data) +} + +func decodeUrlSafe(data string) string { + dcBuf, err := base64.RawURLEncoding.DecodeString(data) + if err != nil { + return "" + } + return string(dcBuf) +} diff --git a/common/convert/converter.go b/common/convert/converter.go index 811acecb..9264200f 100644 --- a/common/convert/converter.go +++ b/common/convert/converter.go @@ -2,7 +2,6 @@ package convert import ( "bytes" - "encoding/base64" "encoding/json" "fmt" "net/url" @@ -10,23 +9,6 @@ import ( "strings" ) -var ( - encRaw = base64.RawStdEncoding - enc = base64.StdEncoding -) - -func DecodeBase64(buf []byte) []byte { - dBuf := make([]byte, encRaw.DecodedLen(len(buf))) - n, err := encRaw.Decode(dBuf, buf) - if err != nil { - n, err = enc.Decode(dBuf, buf) - if err != nil { - return buf - } - } - return dBuf[:n] -} - // ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config func ConvertsV2Ray(buf []byte) ([]map[string]any, error) { data := DecodeBase64(buf) @@ -450,18 +432,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) { return proxies, nil } -func urlSafe(data string) string { - return strings.ReplaceAll(strings.ReplaceAll(data, "+", "-"), "/", "_") -} - -func decodeUrlSafe(data string) string { - dcBuf, err := base64.RawURLEncoding.DecodeString(data) - if err != nil { - return "" - } - return string(dcBuf) -} - func uniqueName(names map[string]int, name string) string { if index, ok := names[name]; ok { index++