diff --git a/cmd/internal/http/server.go b/cmd/internal/http/server.go index 3c8c68c..845097c 100644 --- a/cmd/internal/http/server.go +++ b/cmd/internal/http/server.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "net/http" + "time" "github.com/siestaw/laterna/server/cmd/internal/config" "github.com/siestaw/laterna/server/cmd/internal/db" @@ -39,6 +40,7 @@ func getCurrent(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(state) + defer r.Body.Close() } func setCurrent(w http.ResponseWriter, r *http.Request) { @@ -48,6 +50,16 @@ func setCurrent(w http.ResponseWriter, r *http.Request) { utils.HTTPErrorHandling(w, r, http.StatusBadRequest, err.Error()) return } + currentState, err := db.ViewColor(id) + if err != nil { + utils.HTTPErrorHandling(w, r, http.StatusInternalServerError, "Failed to get current lamp color") + return + } + + if time.Since(currentState.UpdatedAt).Seconds() < config.AppConfig.HTTP.Cooldown { + utils.HTTPErrorHandling(w, r, http.StatusTooManyRequests, "Slow down!") + return + } var req models.LampUpdateRequest if err := json.NewDecoder(r.Body).Decode(&req); err != nil { @@ -63,11 +75,11 @@ func setCurrent(w http.ResponseWriter, r *http.Request) { return } - updatedState, err := db.ViewColor(id) - if err != nil { - utils.HTTPErrorHandling(w, r, http.StatusInternalServerError, "Failed to fetch lamp state") - return - } + updatedState := currentState + updatedState.Color = req.Color + updatedState.UpdatedAt = time.Now() + w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(updatedState) + defer r.Body.Close() } diff --git a/cmd/internal/models/models.go b/cmd/internal/models/models.go index cc42a55..d470586 100644 --- a/cmd/internal/models/models.go +++ b/cmd/internal/models/models.go @@ -3,8 +3,9 @@ package models import "time" type HTTPConfig struct { - AdminToken string `json:"adminToken"` - Port int `json:"port"` + AdminToken string `json:"adminToken"` + Port int `json:"port"` + Cooldown float64 `json:"cooldown"` } type Config struct { diff --git a/config.json.example b/config.json.example index 91f2a56..a8e3e70 100644 --- a/config.json.example +++ b/config.json.example @@ -3,6 +3,7 @@ "verboseLogging": true, "http": { "adminToken": "", - "port": 8080 + "port": 8080, + "cooldown": 5, } } \ No newline at end of file