Files
skillshare/internal/server/middleware.go
T
Willie 344b067806 feat(ui): add SSE streaming for update, check, and diff pages
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
2026-03-05 02:13:21 +08:00

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
}