first commit
This commit is contained in:
58
handlers/upload.go
Normal file
58
handlers/upload.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
|
||||
"aroll/store"
|
||||
)
|
||||
|
||||
// UploadHandler reads the video into memory and stores it in Redis under a
|
||||
// random key. The key is returned to the frontend as "filename".
|
||||
// Nothing is written to disk — the file lives only in Redis with a TTL.
|
||||
func UploadHandler(st *store.Store) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4<<30)
|
||||
if err := r.ParseMultipartForm(64 << 20); err != nil {
|
||||
http.Error(w, "parse form: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := r.FormFile("video")
|
||||
if err != nil {
|
||||
http.Error(w, "missing 'video' field", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
data, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
http.Error(w, "read file: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
ext := filepath.Ext(header.Filename)
|
||||
if ext == "" {
|
||||
ext = ".mp4"
|
||||
}
|
||||
|
||||
// Key format: "video-<id><ext>" e.g. "video-a3f9...2b.mp4"
|
||||
key := "video-" + store.NewID() + ext
|
||||
|
||||
if err := st.Set(context.Background(), key, data); err != nil {
|
||||
http.Error(w, "store: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"filename": key})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user