package endpoints import ( "crypto/rand" "encoding/hex" "io" "mime/multipart" "net/http" "os" "path/filepath" "github.com/gin-gonic/gin" ) func generateID() (string, error) { bytes := make([]byte, 16) if _, err := rand.Read(bytes); err != nil { return "", err } return hex.EncodeToString(bytes), nil } func HandleFileUpload(c *gin.Context) { file, header, err := c.Request.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "No file provided"}) return } defer func(file multipart.File) { err := file.Close() if err != nil { } }(file) fileID, err := generateID() if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate file ID"}) return } uploadsDir := "./uploads" fileDir := filepath.Join(uploadsDir, fileID) if err := os.MkdirAll(fileDir, 0755); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create file directory"}) return } dst := filepath.Join(fileDir, header.Filename) out, err := os.Create(dst) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create file"}) return } defer func(out *os.File) { err := out.Close() if err != nil { } }(out) _, err = io.Copy(out, file) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"}) return } baseURL := os.Getenv("BASE_URL") if baseURL == "" { baseURL = "http://localhost:8080" } fileURL := baseURL + "/files/" + fileID + "/" + header.Filename c.JSON(http.StatusOK, gin.H{ "message": "File uploaded successfully", "id": fileID, "filename": header.Filename, "size": header.Size, "url": fileURL, }) }