util.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package s3
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "io"
  6. "net/url"
  7. "os"
  8. )
  9. // GetBase64MD5Str 计算Base64格式字符串的MD5值
  10. func GetBase64MD5Str(str string) string {
  11. // 创建一个MD5哈希对象
  12. hash := md5.New()
  13. // 将字符串转换为字节数组并计算MD5哈希值
  14. hash.Write([]byte(str))
  15. md5Hash := hash.Sum(nil)
  16. // 将MD5哈希值转换为Base64格式
  17. base64Str := base64.StdEncoding.EncodeToString(md5Hash)
  18. return base64Str
  19. }
  20. // GetBase64Str 计算Base64格式字符串
  21. func GetBase64Str(str string) string {
  22. return base64.StdEncoding.EncodeToString([]byte(str))
  23. }
  24. // GetBase64FileMD5Str 计算Base64格式文件的MD5值
  25. func GetBase64FileMD5Str(filePath string) (string, error) {
  26. file, err := os.Open(filePath)
  27. if err != nil {
  28. return "", err
  29. }
  30. defer file.Close()
  31. hash := md5.New()
  32. if _, err := io.Copy(hash, file); err != nil {
  33. return "", err
  34. }
  35. md5Hash := hash.Sum(nil)
  36. // 将MD5哈希值转换为Base64格式
  37. base64Str := base64.StdEncoding.EncodeToString(md5Hash)
  38. return base64Str, err
  39. }
  40. // BuildCopySource 构建拷贝源
  41. func BuildCopySource(bucket *string, key *string) string {
  42. if bucket == nil || key == nil {
  43. return ""
  44. }
  45. return "/" + *bucket + "/" + url.QueryEscape(*key)
  46. }
  47. // GetCannedACL 获取访问控制权限
  48. func GetCannedACL(Grants []*Grant) string {
  49. allUsersPermissions := map[string]*string{}
  50. for _, value := range Grants {
  51. if value.Grantee.URI != nil && *value.Grantee.URI == AllUsersUri {
  52. allUsersPermissions[*value.Permission] = value.Permission
  53. }
  54. }
  55. _, read := allUsersPermissions["READ"]
  56. _, write := allUsersPermissions["WRITE"]
  57. if read && write {
  58. return ACLPublicReadWrite
  59. } else if read {
  60. return ACLPublicRead
  61. } else {
  62. return ACLPrivate
  63. }
  64. }
  65. // FileExists returns whether the given file exists or not
  66. func FileExists(filename string) bool {
  67. info, err := os.Stat(filename)
  68. if os.IsNotExist(err) {
  69. return false
  70. }
  71. return !info.IsDir()
  72. }
  73. // DirExists returns whether the given directory exists or not
  74. func DirExists(dir string) bool {
  75. info, err := os.Stat(dir)
  76. if os.IsNotExist(err) {
  77. return false
  78. }
  79. return info.IsDir()
  80. }
  81. // Min returns the smaller of two integers
  82. func Min(a, b int64) int64 {
  83. if a < b {
  84. return a
  85. }
  86. return b
  87. }
  88. // IsV4Signature checks if the signer is V4 or V4_UNSIGNED_PAYLOAD_SIGNER
  89. func IsV4Signature(signer string) bool {
  90. return signer == "V4" || signer == "V4_UNSIGNED_PAYLOAD_SIGNER"
  91. }