base64.go 906 B

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