Upload limit

This commit is contained in:
2025-08-08 15:41:02 +02:00
parent 5f35925745
commit 1d0fe30480

View File

@@ -7,6 +7,7 @@ import (
"net/http"
"os"
"path/filepath"
"strconv"
"github.com/gin-gonic/gin"
)
@@ -25,13 +26,56 @@ func HandleFileUpload(c *gin.Context) {
}
defer file.Close()
// Resolve upload directory from environment
uploadDir := os.Getenv("UPLOAD_DIR")
if uploadDir == "" {
uploadDir = "./uploads"
}
// Ensure upload directory exists (so size calc works)
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
}
}
// Read max storage from env and compute current usage
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
}
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)
// If storage is already full, reject upload
if usedBytes >= maxBytes {
c.JSON(http.StatusInsufficientStorage, gin.H{"error": "Storage limit reached. Upload disabled."})
return
}
// If this file would exceed the limit (when size is known), reject upload
if header.Size > 0 && usedBytes+header.Size > maxBytes {
c.JSON(http.StatusInsufficientStorage, gin.H{"error": "Not enough storage available for this upload."})
return
}
fileID, err := generateID()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate file ID"})
return
}
fileDir := filepath.Join("./uploads", fileID)
fileDir := filepath.Join(uploadDir, fileID)
if err := os.MkdirAll(fileDir, 0755); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create file directory"})
return