abyss/helpers.go

52 lines
1020 B
Go
Raw Permalink Normal View History

2024-10-03 21:19:14 -03:00
package main
import (
2024-10-15 14:18:55 -03:00
"crypto/md5"
"encoding/hex"
2024-10-03 21:19:14 -03:00
"fmt"
2024-10-15 14:18:55 -03:00
"io"
2024-10-03 21:19:14 -03:00
"net/http"
2024-10-15 15:08:27 -03:00
"os"
2024-10-03 21:19:14 -03:00
)
func CheckAuth(r *http.Request, key string) bool {
return r.Header.Get("X-Auth") == key
}
func FormatFileSize(size int64) string {
if size < 1024 {
return fmt.Sprintf("%d B", size)
} else if size < 1024*1024 {
return fmt.Sprintf("%.2f KB", float64(size)/1024)
} else if size < 1024*1024*1024 {
return fmt.Sprintf("%.2f MB", float64(size)/(1024*1024))
}
return fmt.Sprintf("%.2f GB", float64(size)/(1024*1024*1024))
}
2024-10-15 14:18:55 -03:00
2024-10-15 14:38:01 -03:00
func HashFile(file io.Reader, extension string) (string, error) {
2024-10-15 14:18:55 -03:00
hasher := md5.New()
if _, err := io.Copy(hasher, file); err != nil {
return "", err
}
sha1Hash := hex.EncodeToString(hasher.Sum(nil))[:8]
2024-10-15 14:38:01 -03:00
filename := fmt.Sprintf("%s%s", sha1Hash, extension)
2024-10-15 14:18:55 -03:00
return filename, nil
}
2024-10-15 15:08:27 -03:00
func SaveFile(name string, file io.Reader) error {
dst, err := os.Create(name)
if err != nil {
return err
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
return err
}
return nil
}