package http_internal import ( "encoding/json" "fmt" "log" "net/http" loadaverage "rpi5-health/internal/load_average" "rpi5-health/internal/memory" "rpi5-health/internal/processor" "rpi5-health/internal/temperature" "rpi5-health/internal/uptime" "time" ) func SSEHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") // For CORS requests w.Header().Set("Access-Control-Allow-Origin", "*") clientGone := r.Context().Done() // Channel to signal client disconnection rc := http.NewResponseController(w) t := time.NewTicker(time.Millisecond * 1000) defer t.Stop() for { select { case <-clientGone: log.Println("Client disconnected") return case <-t.C: resp := buildDashboardResponse() _, err := fmt.Fprintf(w, "data: %s\n\n", resp) if err != nil { return } err = rc.Flush() if err != nil { return } } } } func buildDashboardResponse() []byte { // TODO: proper error handling loadavg, _ := loadaverage.GetLoadAverage() memoryInfo, _ := memory.GetRamInformation() processorInfo := processor.GetCPUInformation() temperatureInfo, _ := temperature.GetTemperatureInformation() uptimeInfo, _ := uptime.GetUptimeInformation() stats := ServerStatistics{ LoadAvgInfo: loadavg, MemoryInfo: memoryInfo, ProcessorInfo: processorInfo, TemperatureInfo: temperatureInfo, UptimeInfo: uptimeInfo, } payload, _ := json.Marshal(stats) return payload }