package main import ( "crypto/rand" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "log/slog" "net/http" "os" "path/filepath" "regexp" "strings" "time" "github.com/go-chi/chi/v5" ) var validIDRegex = regexp.MustCompile(`^[a-zA-Z0-9_\-]+$`) type ComparisonItem struct { Index int `json:"index"` Status any `json:"status"` Latency int64 `json:"latency"` InputFilename string `json:"inputFilename"` OutputFilename string `json:"outputFilename"` ContentType string `json:"contentType"` BeforeImage string `json:"beforeImage"` AfterImage string `json:"afterImage"` TextContent string `json:"textContent"` HasBefore bool `json:"hasBefore"` HasAfter bool `json:"hasAfter"` } type ComparisonShare struct { ID string `json:"id"` Title string `json:"title"` Endpoint string `json:"endpoint"` SpaceName string `json:"spaceName"` CreatedAt string `json:"createdAt"` Total int `json:"total"` SuccessCount int `json:"successCount"` ErrorCount int `json:"errorCount"` AvgLatency int64 `json:"avgLatency"` Items []ComparisonItem `json:"items"` } type ShareRequestItem struct { Index int `json:"index"` Status any `json:"status"` Latency int64 `json:"latency"` InputFilename string `json:"inputFilename"` OutputFilename string `json:"outputFilename"` ContentType string `json:"contentType"` BeforeData string `json:"beforeData"` // base64 or data URL AfterData string `json:"afterData"` // base64 or data URL TextContent string `json:"textContent"` } type ShareRequest struct { Title string `json:"title"` Endpoint string `json:"endpoint"` SpaceName string `json:"spaceName"` Items []ShareRequestItem `json:"items"` } func randomHexString(n int) string { b := make([]byte, n) if _, err := rand.Read(b); err != nil { return fmt.Sprintf("%d", time.Now().UnixNano()) } return hex.EncodeToString(b) } func decodeImageData(dataStr string) ([]byte, string, error) { dataStr = strings.TrimSpace(dataStr) if dataStr == "" { return nil, "", nil } ext := "png" rawB64 := dataStr if strings.HasPrefix(dataStr, "data:") { idx := strings.Index(dataStr, ";base64,") if idx != -1 { mime := dataStr[5:idx] rawB64 = dataStr[idx+8:] switch mime { case "image/jpeg", "image/jpg": ext = "jpg" case "image/webp": ext = "webp" case "image/gif": ext = "gif" case "image/svg+xml": ext = "svg" case "image/avif": ext = "avif" default: ext = "png" } } } // Clean out any newlines/spaces in base64 string rawB64 = strings.ReplaceAll(rawB64, "\r", "") rawB64 = strings.ReplaceAll(rawB64, "\n", "") rawB64 = strings.ReplaceAll(rawB64, " ", "") b, err := base64.StdEncoding.DecodeString(rawB64) if err != nil { b, err = base64.URLEncoding.DecodeString(rawB64) } if err != nil { return nil, "", err } return b, ext, nil } func createComparisonShareHandler(w http.ResponseWriter, r *http.Request) { // Set 500MB limit on request body for batches of images r.Body = http.MaxBytesReader(w, r.Body, 500*1024*1024) var req ShareRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { slog.Error("failed to decode share request", "error", err) writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": "Invalid request body: " + err.Error()}) return } if len(req.Items) == 0 { writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": "No items provided for comparison share"}) return } // Generate clean unique ID shareID := fmt.Sprintf("cmp_%x_%s", time.Now().Unix(), randomHexString(4)) compDir := filepath.Join("data", "bulk-api-tester", "comparisons", shareID) imagesDir := filepath.Join(compDir, "images") if err := os.MkdirAll(imagesDir, 0755); err != nil { slog.Error("failed to create comparison directory", "dir", compDir, "error", err) writeJSON(w, http.StatusInternalServerError, map[string]any{"success": false, "error": "Failed to create storage directory"}) return } var items []ComparisonItem var totalLatency int64 successCount := 0 errorCount := 0 for i, it := range req.Items { itemIndex := it.Index if itemIndex <= 0 { itemIndex = i + 1 } cItem := ComparisonItem{ Index: itemIndex, Status: it.Status, Latency: it.Latency, InputFilename: it.InputFilename, OutputFilename: it.OutputFilename, ContentType: it.ContentType, TextContent: it.TextContent, } // Check status code for success/error count isSuccess := false switch v := it.Status.(type) { case float64: if int(v) >= 200 && int(v) < 300 { isSuccess = true } case int: if v >= 200 && v < 300 { isSuccess = true } case string: if strings.HasPrefix(v, "2") { isSuccess = true } } if isSuccess { successCount++ } else { errorCount++ } totalLatency += it.Latency // Save Before Image if provided if it.BeforeData != "" { beforeBytes, ext, err := decodeImageData(it.BeforeData) if err == nil && len(beforeBytes) > 0 { filename := fmt.Sprintf("before_%d.%s", itemIndex, ext) filePath := filepath.Join(imagesDir, filename) if err := os.WriteFile(filePath, beforeBytes, 0644); err == nil { cItem.BeforeImage = fmt.Sprintf("/api/comparison/%s/images/%s", shareID, filename) cItem.HasBefore = true } else { slog.Warn("failed to write before image", "file", filename, "error", err) } } else if err != nil { slog.Warn("failed to decode before image", "index", itemIndex, "error", err) } } // Save After Image if provided if it.AfterData != "" { afterBytes, ext, err := decodeImageData(it.AfterData) if err == nil && len(afterBytes) > 0 { filename := fmt.Sprintf("after_%d.%s", itemIndex, ext) filePath := filepath.Join(imagesDir, filename) if err := os.WriteFile(filePath, afterBytes, 0644); err == nil { cItem.AfterImage = fmt.Sprintf("/api/comparison/%s/images/%s", shareID, filename) cItem.HasAfter = true } else { slog.Warn("failed to write after image", "file", filename, "error", err) } } else if err != nil { slog.Warn("failed to decode after image", "index", itemIndex, "error", err) } } items = append(items, cItem) } title := req.Title if title == "" { title = fmt.Sprintf("Batch Comparison (%d results)", len(items)) } var avgLatency int64 if len(items) > 0 { avgLatency = totalLatency / int64(len(items)) } shareData := ComparisonShare{ ID: shareID, Title: title, Endpoint: req.Endpoint, SpaceName: req.SpaceName, CreatedAt: time.Now().UTC().Format(time.RFC3339), Total: len(items), SuccessCount: successCount, ErrorCount: errorCount, AvgLatency: avgLatency, Items: items, } metaPath := filepath.Join(compDir, "meta.json") if err := atomicWriteJSON(metaPath, shareData); err != nil { slog.Error("failed to save comparison metadata", "path", metaPath, "error", err) writeJSON(w, http.StatusInternalServerError, map[string]any{"success": false, "error": "Failed to save comparison meta"}) return } slog.Info("created shareable comparison", "share_id", shareID, "items_count", len(items)) writeJSON(w, http.StatusOK, map[string]any{ "success": true, "shareId": shareID, "url": "/tool/bulk-api-tester/compare/" + shareID, "directUrl": "/compare/" + shareID, "total": len(items), }) } func getComparisonDataHandler(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") if id == "" || !validIDRegex.MatchString(id) { writeJSON(w, http.StatusBadRequest, map[string]any{"error": "Invalid comparison ID"}) return } metaPath := filepath.Join("data", "bulk-api-tester", "comparisons", id, "meta.json") var data ComparisonShare if err := readJSON(metaPath, &data); err != nil { writeJSON(w, http.StatusNotFound, map[string]any{"error": "Comparison not found"}) return } w.Header().Set("Cache-Control", "no-cache, must-revalidate") writeJSON(w, http.StatusOK, data) } func getComparisonImageHandler(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") file := chi.URLParam(r, "file") if id == "" || !validIDRegex.MatchString(id) || file == "" { http.Error(w, "Invalid parameters", http.StatusBadRequest) return } cleanFile := filepath.Base(file) if cleanFile != file { http.Error(w, "Invalid filename", http.StatusBadRequest) return } filePath := filepath.Join("data", "bulk-api-tester", "comparisons", id, "images", cleanFile) if _, err := os.Stat(filePath); os.IsNotExist(err) { http.Error(w, "Image not found", http.StatusNotFound) return } ext := strings.ToLower(filepath.Ext(cleanFile)) contentType := "application/octet-stream" switch ext { case ".png": contentType = "image/png" case ".jpg", ".jpeg": contentType = "image/jpeg" case ".webp": contentType = "image/webp" case ".gif": contentType = "image/gif" case ".svg": contentType = "image/svg+xml" case ".avif": contentType = "image/avif" } w.Header().Set("Content-Type", contentType) w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") http.ServeFile(w, r, filePath) } func comparePageHandler(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") if id == "" { id = r.URL.Query().Get("id") } workDir, _ := os.Getwd() htmlPath := filepath.Join(workDir, "web", "bulk-api-tester", "compare.html") htmlBytes, err := os.ReadFile(htmlPath) if err != nil { http.Error(w, "compare.html not found", http.StatusNotFound) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-cache, must-revalidate") // If valid ID provided and meta exists, inject it directly for zero-latency instant render if id != "" && validIDRegex.MatchString(id) { metaPath := filepath.Join("data", "bulk-api-tester", "comparisons", id, "meta.json") if metaBytes, err := os.ReadFile(metaPath); err == nil { injectScript := fmt.Sprintf(``, string(metaBytes)) htmlStr := string(htmlBytes) if strings.Contains(htmlStr, "") { htmlStr = strings.Replace(htmlStr, "", injectScript+"\n", 1) w.Write([]byte(htmlStr)) return } } } w.Write(htmlBytes) }