first commit
This commit is contained in:
96
handlers/files.go
Normal file
96
handlers/files.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slideshowApp/env"
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var (
|
||||
// Keep track of all open slideshow connections
|
||||
clients = make(map[*websocket.Conn]bool)
|
||||
clientsMu sync.Mutex
|
||||
)
|
||||
|
||||
func UploadHandler(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseMultipartForm(50 << 20)
|
||||
files := r.MultipartForm.File["myPictures"]
|
||||
uploadDir := env.PhotoDir.GetValue()
|
||||
os.MkdirAll(uploadDir, os.ModePerm)
|
||||
|
||||
for _, fileHeader := range files {
|
||||
file, _ := fileHeader.Open()
|
||||
dstPath := filepath.Join(uploadDir, fileHeader.Filename)
|
||||
dst, _ := os.Create(dstPath)
|
||||
io.Copy(dst, file)
|
||||
file.Close()
|
||||
dst.Close()
|
||||
}
|
||||
|
||||
// NEW: Tell all slideshows to update their lists
|
||||
notifyClients()
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func ListFilesHandler(w http.ResponseWriter, r *http.Request) {
|
||||
files, err := os.ReadDir(env.PhotoDir.GetValue())
|
||||
if err != nil {
|
||||
http.Error(w, "Unable to read directory", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
var fileNames []string
|
||||
for _, file := range files {
|
||||
if !file.IsDir() {
|
||||
fileNames = append(fileNames, file.Name())
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(fileNames)
|
||||
}
|
||||
|
||||
func DeleteHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// 1. Get filenames from request body
|
||||
var filenames []string
|
||||
err := json.NewDecoder(r.Body).Decode(&filenames)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
uploadDir := env.PhotoDir.GetValue()
|
||||
|
||||
// 2. Delete each file
|
||||
for _, name := range filenames {
|
||||
fullPath := filepath.Join(uploadDir, filepath.Base(name)) // Base() for security
|
||||
os.Remove(fullPath)
|
||||
}
|
||||
|
||||
// 3. Notify slideshows to refresh their lists
|
||||
notifyClients()
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func notifyClients() {
|
||||
clientsMu.Lock()
|
||||
defer clientsMu.Unlock()
|
||||
for client := range clients {
|
||||
err := client.WriteMessage(websocket.TextMessage, []byte("refresh"))
|
||||
if err != nil {
|
||||
client.Close()
|
||||
delete(clients, client)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user