Files
lash/internal/handlers/file.go
2026-05-29 08:05:00 -04:00

72 lines
1.5 KiB
Go

package handlers
import (
"encoding/json"
"fmt"
"lash"
"net/http"
"os"
"strconv"
)
type FileHandler struct {
Ctx *lash.LashContext
FileData FileData
}
type FileData struct {
Contents []byte
FileName string
}
type ValidateRequest struct {
Token string
}
var sent int = 0
func (h FileHandler) APIHandler(w http.ResponseWriter, r *http.Request) {
if sent >= h.Ctx.N && h.Ctx.N != -1 {
w.WriteHeader(http.StatusTooManyRequests)
os.Exit(0)
return
}
decoder := json.NewDecoder(r.Body)
var t ValidateRequest
err := decoder.Decode(&t)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if t.Token != lash.Token {
http.Error(w, "Invalid Token", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", h.FileData.FileName))
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.Itoa(len(h.FileData.Contents)))
w.WriteHeader(http.StatusOK)
w.Write(h.FileData.Contents)
sent++
}
func (h FileHandler) FileHandler(w http.ResponseWriter, r *http.Request) {
if sent >= h.Ctx.N && h.Ctx.N != -1 {
w.WriteHeader(http.StatusTooManyRequests)
os.Exit(0)
return
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", h.FileData.FileName))
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.Itoa(len(h.FileData.Contents)))
w.WriteHeader(http.StatusOK)
w.Write(h.FileData.Contents)
sent++
}