Added storage endpoint and show on indes

This commit is contained in:
2025-08-07 22:38:27 +02:00
parent 716c6730b5
commit c7fd393cbf
6 changed files with 128 additions and 3 deletions

71
controllers/storage.go Normal file
View File

@@ -0,0 +1,71 @@
package controllers
import (
"net/http"
"os"
"path/filepath"
"strconv"
"github.com/gin-gonic/gin"
)
func getDirectorySize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}
func HandleStorageInfo(c *gin.Context) {
uploadDir := os.Getenv("UPLOAD_DIR")
if uploadDir == "" {
uploadDir = "./uploads"
}
maxStorageEnv := os.Getenv("MAX_STORAGE_GB")
if maxStorageEnv == "" {
maxStorageEnv = "10"
}
maxStorageGB, err := strconv.ParseFloat(maxStorageEnv, 64)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid MAX_STORAGE_GB configuration"})
return
}
if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
if err := os.MkdirAll(uploadDir, 0755); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create upload directory"})
return
}
}
usedBytes, err := getDirectorySize(uploadDir)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to calculate storage usage"})
return
}
maxBytes := int64(maxStorageGB * 1024 * 1024 * 1024)
usedGB := float64(usedBytes) / (1024 * 1024 * 1024)
usagePercent := (float64(usedBytes) / float64(maxBytes)) * 100
c.JSON(http.StatusOK, gin.H{
"storage": gin.H{
"used_bytes": usedBytes,
"used_gb": usedGB,
"max_gb": maxStorageGB,
"max_bytes": maxBytes,
"usage_percent": usagePercent,
"available_gb": maxStorageGB - usedGB,
"available_bytes": maxBytes - usedBytes,
},
})
}

View File

@@ -59,6 +59,6 @@ func HandleFileUpload(c *gin.Context) {
"id": fileID,
"filename": header.Filename,
"size": header.Size,
"url": baseURL + "/files/" + fileID + "/" + header.Filename,
"url": baseURL + "/uploads/" + fileID + "/" + header.Filename,
})
}