diff --git a/main.go b/main.go index 56acbfe..06f055e 100644 --- a/main.go +++ b/main.go @@ -149,6 +149,7 @@ func (s *Server) handleConnections(w http.ResponseWriter, r *http.Request) { if err != nil { log.Fatalf("Unable to marshal JSON due to %s", err) } + fmt.Printf("Broadcasting ws message to %d clients", s.clients) s.broadcast <- message } } @@ -199,7 +200,7 @@ func broadcastExpiredRecords(s *Server, removed string) { log.Println("Error marshalling json:", err) return } - fmt.Printf("Broadcasting expiration: %s\n", string(msgJSON)) + fmt.Printf("Broadcasting expiration: %s to %s clients\n", string(msgJSON), len(s.clients)) for client := range s.clients { if err := client.conn.WriteMessage(websocket.TextMessage, msgJSON); err != nil { log.Println("Failed to broadcast update:", err) @@ -266,26 +267,29 @@ func fetchAllRecords() (map[string]string, error) { return records, nil } -func statusCheck(w http.ResponseWriter, r *http.Request) { +func getState(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed) return } - + fmt.Println("Checking Status") var request struct { Id string `json:"Id"` } err := json.NewDecoder(r.Body).Decode(&request) if err != nil { + fmt.Println("Invalid JSON format") + fmt.Println(r.Body) http.Error(w, "Invalid JSON format", http.StatusBadRequest) return } if request.Id == "" { + fmt.Println("Missing or empty Id field") http.Error(w, "Missing or empty Id field", http.StatusBadRequest) return } - + fmt.Println(request.Id) value, err := redisClient.Get(ctx, request.Id).Result() if errors.Is(err, redis.Nil) { message := Message{Id: request.Id, Status: "none", Timestamp: time.Now().Format(time.RFC3339)} @@ -358,6 +362,38 @@ func setState(w http.ResponseWriter, r *http.Request, s *Server) { w.WriteHeader(http.StatusOK) } +func updateState(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "Only GET method is allowed", http.StatusMethodNotAllowed) + return + } + allRecords, err := fetchAllRecords() + if err != nil { + log.Printf("Error fetching records: %v", err) + http.Error(w, "Failed to fetch records", http.StatusInternalServerError) + return + } + + var messages []Message + for _, record := range allRecords { + var message Message + err := json.Unmarshal([]byte(record), &message) + if err != nil { + log.Printf("Error unmarshalling record: %v", err) + http.Error(w, "Failed to parse records", http.StatusInternalServerError) + return + } + messages = append(messages, message) + } + + w.Header().Set("Content-Type", "application/json") + err = json.NewEncoder(w).Encode(messages) + if err != nil { + log.Printf("Error encoding response: %v", err) + http.Error(w, "Failed to encode response", http.StatusInternalServerError) + } +} + func enableCORS(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") // Allow all origins @@ -382,10 +418,11 @@ func main() { // Register routes on the mux router router.HandleFunc("/ws", server.handleConnections).Methods("GET") - router.HandleFunc("/status", statusCheck).Methods("POST") + router.HandleFunc("/get", getState).Methods("POST") router.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) { setState(w, r, server) }).Methods("POST") + router.HandleFunc("/update", updateState).Methods("GET") corsRouter := enableCORS(router) // Start server and other necessary goroutines