github.com/metacubex/mihomo@v1.18.5/common/convert/base64.go (about)

     1  package convert
     2  
     3  import (
     4  	"encoding/base64"
     5  	"strings"
     6  )
     7  
     8  var (
     9  	encRaw = base64.RawStdEncoding
    10  	enc    = base64.StdEncoding
    11  )
    12  
    13  // DecodeBase64 try to decode content from the given bytes,
    14  // which can be in base64.RawStdEncoding, base64.StdEncoding or just plaintext.
    15  func DecodeBase64(buf []byte) []byte {
    16  	result, err := tryDecodeBase64(buf)
    17  	if err != nil {
    18  		return buf
    19  	}
    20  	return result
    21  }
    22  
    23  func tryDecodeBase64(buf []byte) ([]byte, error) {
    24  	dBuf := make([]byte, encRaw.DecodedLen(len(buf)))
    25  	n, err := encRaw.Decode(dBuf, buf)
    26  	if err != nil {
    27  		n, err = enc.Decode(dBuf, buf)
    28  		if err != nil {
    29  			return nil, err
    30  		}
    31  	}
    32  	return dBuf[:n], nil
    33  }
    34  
    35  func urlSafe(data string) string {
    36  	return strings.NewReplacer("+", "-", "/", "_").Replace(data)
    37  }
    38  
    39  func decodeUrlSafe(data string) string {
    40  	dcBuf, err := base64.RawURLEncoding.DecodeString(data)
    41  	if err != nil {
    42  		return ""
    43  	}
    44  	return string(dcBuf)
    45  }