Files
Unified_Dashboard_Suite_Go/cmd/image-manipulator/main.go
T

186 lines
4.3 KiB
Go

package main
import (
"log"
"log/slog"
"net/http"
"os"
"sync"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"unified-dashboard/internal/common"
mymiddleware "unified-dashboard/internal/middleware"
)
type SessionData struct {
SessionID string
BatchRootFolder string
BatchZipName string
CreatedAt time.Time
}
var (
sessionStore = make(map[string]*SessionData)
sessionMutex sync.RWMutex
)
func getSessionData(r *http.Request) *SessionData {
var sessionID string
if cookie, err := r.Cookie("session_id"); err == nil && cookie.Value != "" {
sessionID = cookie.Value
}
if sessionID == "" {
sessionID = r.URL.Query().Get("session_id")
}
if sessionID == "" {
sessionID = r.Header.Get("X-Session-ID")
}
if sessionID == "" {
sessionID = r.FormValue("session_id")
}
if sessionID == "" {
return nil
}
sessionMutex.Lock()
defer sessionMutex.Unlock()
if s, exists := sessionStore[sessionID]; exists {
return s
}
// If session directory exists on disk, reconstruct session data
if validateSession(sessionID) {
s := &SessionData{
SessionID: sessionID,
CreatedAt: time.Now(),
}
sessionStore[sessionID] = s
return s
}
return nil
}
func setSessionData(w http.ResponseWriter, s *SessionData) {
sessionMutex.Lock()
sessionStore[s.SessionID] = s
sessionMutex.Unlock()
http.SetCookie(w, &http.Cookie{
Name: "session_id",
Value: s.SessionID,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
}
func main() {
common.InitLogger("image-manipulator")
r := chi.NewRouter()
r.Use(middleware.RealIP)
r.Use(middleware.RequestID)
r.Use(mymiddleware.RequestLogger)
r.Use(middleware.Recoverer)
// 1GB max upload size
r.Use(middleware.RequestSize(1024 * 1024 * 1024))
scriptName := os.Getenv("SCRIPT_NAME")
if scriptName != "" {
r.Use(common.PrefixMiddleware(scriptName))
}
r.Get("/", indexHandler)
r.Get("/styles.css", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/css; charset=utf-8")
for _, p := range []string{
"cmd/image-manipulator/styles.css",
"web/image-manipulator/styles.css",
} {
if _, err := os.Stat(p); err == nil {
http.ServeFile(w, r, p)
return
}
}
http.NotFound(w, r)
})
r.Get("/app.js", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
for _, p := range []string{
"cmd/image-manipulator/app.js",
"web/image-manipulator/app.js",
} {
if _, err := os.Stat(p); err == nil {
http.ServeFile(w, r, p)
return
}
}
http.NotFound(w, r)
})
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":"ok"}`))
})
r.Post("/resize", resizeHandler)
r.Post("/convert", convertHandler)
r.Post("/compress", compressHandler)
r.Post("/simulate-compression", simulateCompressionHandler)
r.Post("/crop", cropHandler)
r.Post("/filter", filterHandler)
r.Post("/rotate", rotateHandler)
r.Post("/watermark", watermarkHandler)
r.Post("/mask", maskHandler)
r.Post("/download-all", downloadAllHandler)
r.Post("/create-session", createSessionHandler)
r.Post("/upload-batch", uploadBatchHandler)
r.Get("/preview-batch", previewBatchHandler)
r.Post("/batch-process-session", batchProcessSessionHandler)
r.Get("/download-batch", downloadBatchHandler)
r.Head("/download-batch", downloadBatchHandler)
// Start cleanup goroutine
go func() {
for {
time.Sleep(5 * time.Minute)
cleanupOldSessions()
// Clean memory store
sessionMutex.Lock()
now := time.Now()
for id, s := range sessionStore {
if now.Sub(s.CreatedAt) > time.Hour {
delete(sessionStore, id)
}
}
sessionMutex.Unlock()
}
}()
port := os.Getenv("PORT")
if port == "" {
port = "5001"
}
slog.Info("starting image-manipulator", "port", port, "pid", os.Getpid())
if err := http.ListenAndServe("0.0.0.0:"+port, r); err != nil {
log.Fatal(err)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
for _, p := range []string{
"web/image-manipulator/index.html",
"cmd/image-manipulator/index.html",
} {
if _, err := os.Stat(p); err == nil {
http.ServeFile(w, r, p)
return
}
}
http.NotFound(w, r)
}