feat: add getting computer data route

This commit is contained in:
trafficlunar 2024-11-29 18:06:28 +00:00
parent 840e584082
commit 58adca9cd0
4 changed files with 34 additions and 0 deletions

View file

@ -2,6 +2,7 @@ package handler
import ( import (
"backend/internal/model" "backend/internal/model"
"backend/internal/service"
"encoding/json" "encoding/json"
"log/slog" "log/slog"
"net/http" "net/http"
@ -25,12 +26,14 @@ func HandleComputerWebSocket(w http.ResponseWriter, r *http.Request) {
defer conn.Close() defer conn.Close()
slog.Info("Websocket connection established!") slog.Info("Websocket connection established!")
online := true
// Read messages // Read messages
for { for {
_, message, err := conn.ReadMessage() _, message, err := conn.ReadMessage()
if err != nil { if err != nil {
slog.Error("WebSocket connection closed by client", slog.Any("error", err)) slog.Error("WebSocket connection closed by client", slog.Any("error", err))
online = false
break break
} }
@ -40,6 +43,12 @@ func HandleComputerWebSocket(w http.ResponseWriter, r *http.Request) {
continue continue
} }
service.AddComputerData(online, clientMessage)
slog.Info("Recieved message", slog.Any("message", clientMessage)) slog.Info("Recieved message", slog.Any("message", clientMessage))
} }
} }
func HandleComputerGraphData(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(service.ComputerData)
}

View file

@ -4,3 +4,9 @@ type ComputerWebSocketMessage struct {
Cpu uint8 `json:"cpu"` Cpu uint8 `json:"cpu"`
Ram uint8 `json:"ram"` Ram uint8 `json:"ram"`
} }
type ComputerGraphData struct {
Online bool `json:"online"`
Cpu []int `json:"cpu"`
Ram []int `json:"ram"`
}

View file

@ -42,6 +42,7 @@ func NewRouter() {
r.Get("/currently-playing", handler.HandleGetCurrentlyPlaying) r.Get("/currently-playing", handler.HandleGetCurrentlyPlaying)
r.Get("/status", handler.HandleGetStatus) r.Get("/status", handler.HandleGetStatus)
r.Get("/computer", handler.HandleComputerGraphData)
r.Get("/ws/computer", handler.HandleComputerWebSocket) r.Get("/ws/computer", handler.HandleComputerWebSocket)
port := os.Getenv("PORT") port := os.Getenv("PORT")

View file

@ -0,0 +1,18 @@
package service
import (
"backend/internal/model"
)
var ComputerData model.ComputerGraphData
func AddComputerData(online bool, clientMessage model.ComputerWebSocketMessage) {
ComputerData.Online = online
ComputerData.Cpu = append(ComputerData.Cpu, int(clientMessage.Cpu))
ComputerData.Ram = append(ComputerData.Ram, int(clientMessage.Ram))
if len(ComputerData.Cpu) > 20 {
ComputerData.Cpu = ComputerData.Cpu[1:]
ComputerData.Ram = ComputerData.Ram[1:]
}
}