mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-19 02:17:09 +00:00
Replace sequential POST loops and blocking useQuery calls with Server-Sent Events for real-time progress feedback on Update, Check, and Diff operations. Extract shared helpers to reduce duplication: - initSSE() in middleware.go consolidates SSE preamble across 4 handlers - createSSEStream() in client.ts unifies EventSource lifecycle management - StreamProgressBar component replaces 3 near-identical progress bars - handleDiff now delegates to computeTargetDiff (eliminates ~150 lines) - Paginate audit results (20 cards + 10 findings per card) to prevent DOM overload with large skill counts
56 lines
1.6 KiB
Go
56 lines
1.6 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// writeJSON writes a JSON response with 200 status
|
|
func writeJSON(w http.ResponseWriter, data any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(data)
|
|
}
|
|
|
|
// writeError writes a JSON error response
|
|
func writeError(w http.ResponseWriter, code int, msg string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(code)
|
|
json.NewEncoder(w).Encode(map[string]string{"error": msg})
|
|
}
|
|
|
|
// sendSSE writes a single Server-Sent Event frame and flushes.
|
|
func sendSSE(w http.ResponseWriter, f http.Flusher, event string, data any) {
|
|
b, err := json.Marshal(data)
|
|
if err != nil {
|
|
return
|
|
}
|
|
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, b)
|
|
f.Flush()
|
|
}
|
|
|
|
// initSSE sets SSE headers, disables the write deadline, and returns a
|
|
// mutex-protected safeSend function. If the ResponseWriter does not support
|
|
// flushing, an error response is written and ok is false.
|
|
func initSSE(w http.ResponseWriter) (safeSend func(string, any), ok bool) {
|
|
flusher, isFlusher := w.(http.Flusher)
|
|
if !isFlusher {
|
|
writeError(w, http.StatusInternalServerError, "streaming not supported")
|
|
return nil, false
|
|
}
|
|
if rc := http.NewResponseController(w); rc != nil {
|
|
_ = rc.SetWriteDeadline(time.Time{})
|
|
}
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
w.Header().Set("Connection", "keep-alive")
|
|
var mu sync.Mutex
|
|
return func(event string, data any) {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
sendSSE(w, flusher, event, data)
|
|
}, true
|
|
}
|