Compare commits

..

No commits in common. "779de059af026cf5f8b20e2f642bb98b1d6503bc" and "807bc66acbac8bcdd9ee909291e2733235c0a9f5" have entirely different histories.

89
main.go
View File

@ -32,7 +32,6 @@ type Message struct {
Name string `json:"Name"` Name string `json:"Name"`
Image string `json:"Image"` Image string `json:"Image"`
Status string `json:"Status"` Status string `json:"Status"`
Theme string `json:"Theme"`
Timestamp string `json:"Timestamp"` Timestamp string `json:"Timestamp"`
} }
@ -45,7 +44,6 @@ type Config struct {
type Client struct { type Client struct {
conn *websocket.Conn conn *websocket.Conn
mu sync.Mutex
} }
type Server struct { type Server struct {
@ -112,7 +110,7 @@ func (s *Server) addClient(client *Client) {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
s.clients[client] = true s.clients[client] = true
sendAllRecordsToClient(client) broadcastAllRecordsToClient(client)
} }
func (s *Server) removeClient(client *Client) { func (s *Server) removeClient(client *Client) {
@ -156,30 +154,62 @@ func (s *Server) handleConnections(w http.ResponseWriter, r *http.Request) {
} }
} }
func broadcastSingleRecord(s *Server, message Message) { func broadcastAllRecords(s *Server) {
allRecords, err := fetchAllRecords()
if err != nil {
log.Println("Error fetching all records:", err)
}
if len(allRecords) > 0 {
var message Message
for _, msgContent := range allRecords {
err = json.Unmarshal([]byte(msgContent), &message)
if err != nil {
log.Println("Unable to marshal JSON due to: ", err)
}
fmt.Printf("Broadcasting %s,%s,%s,%s to %d clients\n", message.Id, message.Status, message.Name, message.Timestamp, len(s.clients))
for client := range s.clients { for client := range s.clients {
sendMessageToClient(client, message) if err := client.conn.WriteMessage(websocket.TextMessage, []byte(msgContent)); err != nil {
log.Println("Failed to broadcast update:", err)
}
}
}
} }
} }
func sendMessageToClient(client *Client, message Message) { func broadcastRemovedRecords(s *Server, message Message) {
var msgJSON, err = json.Marshal(message) var msgJSON, err = json.Marshal(message)
if err != nil { if err != nil {
log.Println("Error marshalling json:", err) log.Println("Error marshalling json:", err)
return return
} }
go sendToClient(client, msgJSON) fmt.Printf("Broadcasting removal: %s,%s,%s,%s to %d clients\n", message.Id, message.Status, message.Name, message.Timestamp, len(s.clients))
}
func sendToClient(client *Client, msgJSON []byte) { for client := range s.clients {
client.mu.Lock()
defer client.mu.Unlock()
if err := client.conn.WriteMessage(websocket.TextMessage, msgJSON); err != nil { if err := client.conn.WriteMessage(websocket.TextMessage, msgJSON); err != nil {
log.Println("Failed to send message to client:", err) log.Println("Failed to broadcast update:", err)
return
}
} }
} }
func sendAllRecordsToClient(client *Client) { func broadcastExpiredRecords(s *Server, removed string) {
var message = Message{Id: removed, Name: "", Image: "", Status: "removed", Timestamp: ""}
var msgJSON, err = json.Marshal(message)
if err != nil {
log.Println("Error marshalling json:", err)
return
}
fmt.Printf("Broadcasting expiration: %s to %d 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)
return
}
}
}
func broadcastAllRecordsToClient(c *Client) {
allRecords, err := fetchAllRecords() allRecords, err := fetchAllRecords()
if err != nil { if err != nil {
log.Println("Error fetching all records:", err) log.Println("Error fetching all records:", err)
@ -191,8 +221,10 @@ func sendAllRecordsToClient(client *Client) {
if err != nil { if err != nil {
log.Println("Unable to marshal JSON due to: ", err) log.Println("Unable to marshal JSON due to: ", err)
} }
fmt.Printf("Broadcasting %s,%s,%s,%s,%s\n", message.Id, message.Status, message.Name, message.Theme, message.Timestamp) fmt.Printf("Broadcasting %s,%s,%s,%s\n", message.Id, message.Status, message.Name, message.Timestamp)
go sendToClient(client, []byte(msgContent)) if err := c.conn.WriteMessage(websocket.TextMessage, []byte(msgContent)); err != nil {
log.Println("Failed to broadcast update:", err)
}
} }
} }
@ -201,7 +233,7 @@ func (s *Server) listenForExpirationEvents() {
defer func(ps *redis.PubSub) { defer func(ps *redis.PubSub) {
err := ps.Close() err := ps.Close()
if err != nil { if err != nil {
log.Println("Error closing redis pubsub:", err)
} }
}(ps) }(ps)
@ -210,9 +242,8 @@ func (s *Server) listenForExpirationEvents() {
expiredID := msg.Payload expiredID := msg.Payload
fmt.Println(expiredID) fmt.Println(expiredID)
// Broadcast expiration event // Broadcast expiration event
var message = Message{Id: expiredID, Name: "", Image: "", Status: "removed", Theme: "", Timestamp: ""} broadcastExpiredRecords(s, expiredID)
fmt.Printf("Broadcasting expiration: %s to %d clients\n", message, len(s.clients)) fmt.Printf("Done Broadcasting Expiration\n")
broadcastSingleRecord(s, message)
} }
} }
@ -232,9 +263,11 @@ func fetchAllRecords() (map[string]string, error) {
} }
records[key] = value records[key] = value
} }
return records, nil return records, nil
} }
/*
func getState(w http.ResponseWriter, r *http.Request) { func getState(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost { if r.Method != http.MethodPost {
http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed) http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
@ -251,7 +284,7 @@ func getState(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Invalid JSON format", http.StatusBadRequest) http.Error(w, "Invalid JSON format", http.StatusBadRequest)
return return
} }
fmt.Println(request)
if request.Id == "" { if request.Id == "" {
fmt.Println("Missing or empty Id field") fmt.Println("Missing or empty Id field")
http.Error(w, "Missing or empty Id field", http.StatusBadRequest) http.Error(w, "Missing or empty Id field", http.StatusBadRequest)
@ -287,7 +320,7 @@ func getState(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Failed to encode response", http.StatusInternalServerError) http.Error(w, "Failed to encode response", http.StatusInternalServerError)
} }
} }
*/
func setState(w http.ResponseWriter, r *http.Request, s *Server) { func setState(w http.ResponseWriter, r *http.Request, s *Server) {
if r.Method != http.MethodPost { if r.Method != http.MethodPost {
http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed) http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
@ -307,13 +340,17 @@ func setState(w http.ResponseWriter, r *http.Request, s *Server) {
http.Error(w, "Failed to delete key from Redis", http.StatusInternalServerError) http.Error(w, "Failed to delete key from Redis", http.StatusInternalServerError)
return return
} }
fmt.Printf("Broadcasting removal: %s,%s,%s,%s to %d clients\n", message.Id, message.Status, message.Name, message.Timestamp, len(s.clients)) broadcastRemovedRecords(s, message)
} else { w.WriteHeader(http.StatusOK)
return
}
msgJSON, err := json.Marshal(message) msgJSON, err := json.Marshal(message)
if err != nil { if err != nil {
http.Error(w, "Failed to encode message", http.StatusInternalServerError) http.Error(w, "Failed to encode message", http.StatusInternalServerError)
return return
} }
timeout := 20 * time.Second timeout := 20 * time.Second
err = redisClient.Set(ctx, message.Id, msgJSON, timeout).Err() err = redisClient.Set(ctx, message.Id, msgJSON, timeout).Err()
if err != nil { if err != nil {
@ -321,10 +358,8 @@ func setState(w http.ResponseWriter, r *http.Request, s *Server) {
http.Error(w, "Failed to store data", http.StatusInternalServerError) http.Error(w, "Failed to store data", http.StatusInternalServerError)
return return
} }
fmt.Printf("Broadcasting message: %s,%s,%s,%s,%s to %d clients\n", message.Id, message.Status, message.Name, message.Theme, message.Timestamp, len(s.clients))
}
broadcastSingleRecord(s, message) broadcastAllRecords(s)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
} }
@ -385,7 +420,7 @@ func main() {
// Register routes on the mux router // Register routes on the mux router
router.HandleFunc("/ws", server.handleConnections).Methods("GET") router.HandleFunc("/ws", server.handleConnections).Methods("GET")
router.HandleFunc("/get", getState).Methods("POST") //router.HandleFunc("/get", getState).Methods("POST")
router.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) { router.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) {
setState(w, r, server) setState(w, r, server)
}).Methods("POST") }).Methods("POST")