decode.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/axgle/mahonia"
  5. )
  6. func decodeFilename(filename string) (string, error) {
  7. decoded, err := decodeUTF8(filename)
  8. if err == nil {
  9. return decoded, nil
  10. }
  11. // 如果解码失败,尝试其他编码
  12. // 在此处添加其他编码的处理逻辑,例如GBK、Big5等。
  13. // 如果您知道文件名的正确编码,请在此处进行相应的转换。
  14. return filename, nil
  15. }
  16. func decodeUTF8(s string) (string, error) {
  17. decoded, err := decodeString(s, "UTF-8")
  18. if err != nil {
  19. return "", err
  20. }
  21. return decoded, nil
  22. }
  23. func decodeString(s, enc string) (string, error) {
  24. encodings := []string{enc, "GBK", "Big5"} // 根据需要添加其他编码
  25. for _, encoding := range encodings {
  26. decoded, err := decode(s, encoding)
  27. if err == nil {
  28. return decoded, nil
  29. }
  30. }
  31. return s, fmt.Errorf("无法解码字符串:%s", s)
  32. }
  33. func decode(s, enc string) (string, error) {
  34. dec := mahonia.NewDecoder(enc)
  35. if dec == nil {
  36. return "", fmt.Errorf("不支持的编码:%s", enc)
  37. }
  38. return dec.ConvertString(s), nil
  39. }