|
| 1 | +package handlers |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "log" |
| 6 | + "net/http" |
| 7 | + |
| 8 | + "resource-monitor/backend/types" |
| 9 | + "resource-monitor/backend/utils" |
| 10 | + |
| 11 | + "resource-monitor/backend/monitor" |
| 12 | +) |
| 13 | + |
| 14 | +var ShutdownChan = make(chan struct{}) |
| 15 | + |
| 16 | +func ResourceUsageHandler(w http.ResponseWriter, r *http.Request) { |
| 17 | + usage := types.ResourceUsage{ |
| 18 | + CPUUsage: utils.GetCPUUsage(), |
| 19 | + MemoryUsage: utils.GetMemoryUsage(), |
| 20 | + DiskUsage: utils.GetDiskUsage(), |
| 21 | + } |
| 22 | + w.Header().Set("Content-Type", "application/json") |
| 23 | + json.NewEncoder(w).Encode(usage) |
| 24 | +} |
| 25 | + |
| 26 | +func ToggleAlertHandler(w http.ResponseWriter, r *http.Request) { |
| 27 | + if r.Method != http.MethodPost { |
| 28 | + http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) |
| 29 | + return |
| 30 | + } |
| 31 | + |
| 32 | + var data struct { |
| 33 | + EnableAlerts bool `json:"enable_alerts"` |
| 34 | + } |
| 35 | + |
| 36 | + if err := json.NewDecoder(r.Body).Decode(&data); err != nil { |
| 37 | + http.Error(w, "Invalid request", http.StatusBadRequest) |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + monitor.Mu.Lock() |
| 42 | + monitor.AlertEnabled = data.EnableAlerts |
| 43 | + monitor.Mu.Unlock() |
| 44 | + |
| 45 | + log.Printf("Alerts enabled: %v", data.EnableAlerts) |
| 46 | + w.WriteHeader(http.StatusOK) |
| 47 | +} |
| 48 | + |
| 49 | +func ToggleLimitHandler(w http.ResponseWriter, r *http.Request) { |
| 50 | + if r.Method != http.MethodPost { |
| 51 | + http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) |
| 52 | + return |
| 53 | + } |
| 54 | + |
| 55 | + var data types.SetLimit |
| 56 | + if err := json.NewDecoder(r.Body).Decode(&data); err != nil { |
| 57 | + http.Error(w, "Invalid request", http.StatusBadRequest) |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + monitor.Mu.Lock() |
| 62 | + monitor.DefaultLimit = data |
| 63 | + monitor.Mu.Unlock() |
| 64 | + |
| 65 | + log.Printf("Updated limits - CPU: %.2f, Memory: %.2f, Disk: %.2f", data.CPUThreshold, data.MemoryThreshold, data.DiskThreshold) |
| 66 | + w.Header().Set("Content-Type", "application/json") |
| 67 | + json.NewEncoder(w).Encode(data) |
| 68 | +} |
| 69 | + |
| 70 | +func ShutdownHandler(w http.ResponseWriter, r *http.Request) { |
| 71 | + if r.Method == http.MethodPost { |
| 72 | + log.Println("Received shutdown request") |
| 73 | + close(ShutdownChan) |
| 74 | + w.WriteHeader(http.StatusOK) |
| 75 | + } else { |
| 76 | + http.Error(w, "Invalid request method", http.StatusMethodNotAllowed) |
| 77 | + } |
| 78 | +} |
0 commit comments