init
This commit is contained in:
80
src/handlers.go
Normal file
80
src/handlers.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func uploadHandler(c *gin.Context) {
|
||||
file, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"error": "No file uploaded"})
|
||||
return
|
||||
}
|
||||
|
||||
id := uuid.New().String()
|
||||
delID := uuid.New().String()
|
||||
// Secure the filename to prevent path traversal attacks
|
||||
cleanName := filepath.Base(file.Filename)
|
||||
storagePath := filepath.Join("uploads", id+"_"+cleanName)
|
||||
|
||||
if err := c.SaveUploadedFile(file, storagePath); err != nil {
|
||||
c.JSON(500, gin.H{"error": "Failed to save file"})
|
||||
return
|
||||
}
|
||||
|
||||
expiry := time.Now().Add(time.Hour * 24) // Default 24h
|
||||
|
||||
record := FileRecord{
|
||||
ID: id,
|
||||
DeletionID: delID,
|
||||
Filename: cleanName,
|
||||
Path: storagePath,
|
||||
ExpiresAt: expiry,
|
||||
DeleteAfterDownload: c.PostForm("once") == "true",
|
||||
}
|
||||
|
||||
db.Create(&record)
|
||||
|
||||
c.JSON(200, gin.H{
|
||||
"id": id,
|
||||
"deletion_id": delID,
|
||||
"filename": cleanName,
|
||||
"download_url": fmt.Sprintf("/f/%s", id),
|
||||
})
|
||||
}
|
||||
|
||||
func downloadHandler(c *gin.Context) {
|
||||
var record FileRecord
|
||||
if err := db.First(&record, "id = ? AND deleted = ?", c.Param("id"), false).Error; err != nil {
|
||||
c.String(404, "File not found or expired")
|
||||
return
|
||||
}
|
||||
|
||||
if time.Now().After(record.ExpiresAt) {
|
||||
performDeletion(&record)
|
||||
c.String(410, "File has expired")
|
||||
return
|
||||
}
|
||||
|
||||
c.FileAttachment(record.Path, record.Filename)
|
||||
|
||||
db.Model(&record).Update("download_count", record.DownloadCount+1)
|
||||
if record.DeleteAfterDownload {
|
||||
performDeletion(&record)
|
||||
}
|
||||
}
|
||||
|
||||
func deleteHandler(c *gin.Context) {
|
||||
var record FileRecord
|
||||
if err := db.First(&record, "deletion_id = ?", c.Param("del_id")).Error; err != nil {
|
||||
c.JSON(404, gin.H{"error": "Invalid deletion ID"})
|
||||
return
|
||||
}
|
||||
performDeletion(&record)
|
||||
c.JSON(200, gin.H{"message": "Deleted successfully"})
|
||||
}
|
||||
Reference in New Issue
Block a user