Code cleanup

This commit is contained in:
Dominic Ferrando
2025-04-24 00:14:09 -04:00
parent eb770416d0
commit 27fc9476fa
6 changed files with 85 additions and 78 deletions
+64
View File
@@ -0,0 +1,64 @@
package util
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"net"
"net/http"
"strings"
)
const DevMode = false
func FormatBytes(bytes int64) string {
const (
KB = 1 << 10 // 1024
MB = 1 << 20
GB = 1 << 30
TB = 1 << 40
)
switch {
case bytes >= TB:
return fmt.Sprintf("%.2f TB", float64(bytes)/float64(TB))
case bytes >= GB:
return fmt.Sprintf("%.2f GB", float64(bytes)/float64(GB))
case bytes >= MB:
return fmt.Sprintf("%.2f MB", float64(bytes)/float64(MB))
case bytes >= KB:
return fmt.Sprintf("%.2f KB", float64(bytes)/float64(KB))
default:
return fmt.Sprintf("%d B", bytes)
}
}
func GetIP(r *http.Request) string {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
parts := strings.Split(xff, ",")
return strings.TrimSpace(parts[0])
}
// Fallback to RemoteAddr
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return ip
}
func HashIp(ip string) string {
checksum := sha256.Sum256([]byte(ip))
return hex.EncodeToString(checksum[:])
}
func GenToken() (string, error) {
bytes := make([]byte, 32)
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}