Skip to content

Commit

Permalink
修复文件size与实际差异问题
Browse files Browse the repository at this point in the history
- 增加SHA256方法
- 字节单位format,修改为按1024计算
- 修改Copy成功的日志描述
  • Loading branch information
jorben committed Mar 17, 2024
1 parent bc176ba commit 474ba78
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
31 changes: 28 additions & 3 deletions helper/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package helper

import (
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
Expand Down Expand Up @@ -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为单位
}
Expand Down
2 changes: 1 addition & 1 deletion helper/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))))
Expand Down
2 changes: 1 addition & 1 deletion storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down

0 comments on commit 474ba78

Please sign in to comment.