From 474ba78e65c7638217c4ce45ebf4f7ff91e1e9ba Mon Sep 17 00:00:00 2001 From: Jorben Date: Sun, 17 Mar 2024 21:40:21 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=96=87=E4=BB=B6size?= =?UTF-8?q?=E4=B8=8E=E5=AE=9E=E9=99=85=E5=B7=AE=E5=BC=82=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 增加SHA256方法 - 字节单位format,修改为按1024计算 - 修改Copy成功的日志描述 --- helper/file.go | 31 ++++++++++++++++++++++++++++--- helper/string.go | 2 +- storage.go | 2 +- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/helper/file.go b/helper/file.go index f16fa55..ee56496 100644 --- a/helper/file.go +++ b/helper/file.go @@ -2,6 +2,7 @@ package helper import ( "crypto/md5" + "crypto/sha256" "encoding/hex" "fmt" "io" @@ -97,9 +98,33 @@ func Md5(path string) (string, error) { return md5Checksum, nil } -// ByteCountSI 将字节为单位的大小转换为易读的字符串格式 -func ByteCountSI(b int64) string { - const unit = 1000 // 使用SI标准,1KB = 1000B +// Sha256 计算文件的SHA256 +func Sha256(path string) (string, error) { + // 打开文件 + file, err := os.Open(path) + if err != nil { + return "", err + } + defer file.Close() + + // 创建一个新的SHA256哈希计算器 + hash := sha256.New() + + // 读取文件内容并更新哈希计算器 + if _, err := io.Copy(hash, file); err != nil { + return "", err + } + + // 计算最终的哈希值 + sum := hash.Sum(nil) + + // 将哈希值转换为十六进制字符串 + return fmt.Sprintf("%x", sum), nil +} + +// ByteFormat 将字节为单位的大小转换为易读的字符串格式 +func ByteFormat(b int64) string { + const unit = 1024 if b < unit { return fmt.Sprintf("%d B", b) // 小于1KB直接以B为单位 } diff --git a/helper/string.go b/helper/string.go index f4762a4..0f82986 100644 --- a/helper/string.go +++ b/helper/string.go @@ -26,7 +26,7 @@ func HideSecret(secret string, count uint32) string { // RandomString 生成指定长度的随机字符串 func RandomString(length int) (string, error) { - charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" b := make([]byte, length) for i := range b { n, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset)))) diff --git a/storage.go b/storage.go index 255d5c3..4268f16 100644 --- a/storage.go +++ b/storage.go @@ -144,7 +144,7 @@ func (s *Storage) FPutObject(ctx context.Context, localPath string) error { tmp = "./." + randomString fileSize, err := helper.Copy(localPath, tmp) if err == nil { - log.Debugf("Copy success, size %s", helper.ByteCountSI(fileSize)) + log.Debugf("Copy is ready, size %s", helper.ByteFormat(fileSize)) defer os.Remove(tmp) } else { log.Errorf("Copy err: %s", err.Error())