Cleaned code
This commit is contained in:
@@ -4,7 +4,6 @@ import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -14,10 +13,8 @@ import (
|
||||
|
||||
func generateID() (string, error) {
|
||||
bytes := make([]byte, 16)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(bytes), nil
|
||||
_, err := rand.Read(bytes)
|
||||
return hex.EncodeToString(bytes), err
|
||||
}
|
||||
|
||||
func HandleFileUpload(c *gin.Context) {
|
||||
@@ -26,12 +23,7 @@ func HandleFileUpload(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "No file provided"})
|
||||
return
|
||||
}
|
||||
defer func(file multipart.File) {
|
||||
err := file.Close()
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
}(file)
|
||||
defer file.Close()
|
||||
|
||||
fileID, err := generateID()
|
||||
if err != nil {
|
||||
@@ -39,28 +31,20 @@ func HandleFileUpload(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
uploadsDir := "./uploads"
|
||||
fileDir := filepath.Join(uploadsDir, fileID)
|
||||
fileDir := filepath.Join("./uploads", 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)
|
||||
out, err := os.Create(filepath.Join(fileDir, header.Filename))
|
||||
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 {
|
||||
defer out.Close()
|
||||
|
||||
}
|
||||
}(out)
|
||||
|
||||
_, err = io.Copy(out, file)
|
||||
if err != nil {
|
||||
if _, err = io.Copy(out, file); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"})
|
||||
return
|
||||
}
|
||||
@@ -69,14 +53,12 @@ func HandleFileUpload(c *gin.Context) {
|
||||
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,
|
||||
"url": baseURL + "/files/" + fileID + "/" + header.Filename,
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user