mirror of
https://github.com/kaaninchen/Laterna.git
synced 2026-09-17 19:12:48 +00:00
feat: improve responses
This commit is contained in:
@@ -11,7 +11,7 @@ func WithAdminAuth(handlerFunc http.HandlerFunc) http.HandlerFunc {
|
|||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
token := r.Header.Get("Authorization")
|
token := r.Header.Get("Authorization")
|
||||||
if !db.IsAdmin(token) {
|
if !db.IsAdmin(token) {
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusUnauthorized, "Invalid token")
|
utils.ErrorResponse(w, http.StatusUnauthorized, "Invalid token")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
handlerFunc(w, r)
|
handlerFunc(w, r)
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ type HTTPConfig struct {
|
|||||||
Cooldown float64 `json:"cooldown"`
|
Cooldown float64 `json:"cooldown"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
HTTP HTTPConfig `json:"http"`
|
HTTP HTTPConfig `json:"http"`
|
||||||
FileLogging bool `json:"fileLogging"`
|
FileLogging bool `json:"fileLogging"`
|
||||||
@@ -18,11 +17,10 @@ type Config struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type HTTPResponse struct {
|
type HTTPResponse struct {
|
||||||
|
Success bool `json:"success"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
Timestamp string `json:"timestamp"`
|
Timestamp string `json:"timestamp"`
|
||||||
Status int `json:"status"`
|
Data any `json:"data,omitempty"`
|
||||||
Text string `json:"text"`
|
|
||||||
Message string `json:"message"`
|
|
||||||
Path string `json:"path"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type LampState struct {
|
type LampState struct {
|
||||||
@@ -38,3 +36,11 @@ type LampUpdateRequest struct {
|
|||||||
type ControllerRequests struct {
|
type ControllerRequests struct {
|
||||||
ID int `json:"ID"`
|
ID int `json:"ID"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type DeleteData struct {
|
||||||
|
Deleted int `json:"deleted"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateData struct {
|
||||||
|
Created int `json:"created"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
func RegisterColorRoutes(mux *http.ServeMux) {
|
func RegisterColorRoutes(mux *http.ServeMux) {
|
||||||
mux.HandleFunc("GET /api/v1/colors/{ID}", middleware.WithAdminAuth(getCurrent))
|
mux.HandleFunc("GET /api/v1/colors/{ID}", middleware.WithAdminAuth(getCurrent))
|
||||||
mux.HandleFunc("PUT /api/v1/colors/{ID}", middleware.WithAdminAuth(setCurrent))
|
mux.HandleFunc("PUT /api/v1/colors/{ID}", middleware.WithAdminAuth(setCurrent))
|
||||||
// mux.HandleFunc("WS /api/v1/ws/colors/{ID}", setCurrentWebsocket)
|
// mux.HandleFunc("WS /api/v1/ws/colors/{ID}", setCurrentWebsocket)
|
||||||
}
|
}
|
||||||
|
|
||||||
func getCurrent(w http.ResponseWriter, r *http.Request) {
|
func getCurrent(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -25,23 +25,22 @@ func getCurrent(w http.ResponseWriter, r *http.Request) {
|
|||||||
idStr := r.PathValue("ID")
|
idStr := r.PathValue("ID")
|
||||||
id, err := utils.IDtoInt(idStr)
|
id, err := utils.IDtoInt(idStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusBadRequest, err.Error())
|
utils.ErrorResponse(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !db.ControllerExists(id) {
|
if !db.ControllerExists(id) {
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusBadRequest, "Lamp does not exist")
|
utils.ErrorResponse(w, http.StatusNotFound, "Lamp does not exist")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
state, err := db.ViewColor(id)
|
state, err := db.ViewColor(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusBadRequest, err.Error())
|
utils.ErrorResponse(w, http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
utils.SuccessResponse(w, http.StatusOK, state)
|
||||||
json.NewEncoder(w).Encode(state)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func setCurrent(w http.ResponseWriter, r *http.Request) {
|
func setCurrent(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -50,44 +49,42 @@ func setCurrent(w http.ResponseWriter, r *http.Request) {
|
|||||||
idStr := r.PathValue("ID")
|
idStr := r.PathValue("ID")
|
||||||
id, err := utils.IDtoInt(idStr)
|
id, err := utils.IDtoInt(idStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusBadRequest, err.Error())
|
utils.ErrorResponse(w, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !db.ControllerExists(id) {
|
if !db.ControllerExists(id) {
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusBadRequest, "Lamp does not exist")
|
utils.ErrorResponse(w, http.StatusBadRequest, "Lamp does not exist")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
currentState, err := db.ViewColor(id)
|
currentState, err := db.ViewColor(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusInternalServerError, "Failed to get current lamp color")
|
utils.ErrorResponse(w, http.StatusInternalServerError, "Failed to get current lamp color")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if time.Since(currentState.UpdatedAt).Seconds() < config.AppConfig.HTTP.Cooldown {
|
if time.Since(currentState.UpdatedAt).Seconds() < config.AppConfig.HTTP.Cooldown {
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusTooManyRequests, "Slow down!")
|
utils.ErrorResponse(w, http.StatusTooManyRequests, "Slow down!")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var req models.LampUpdateRequest
|
var req models.LampUpdateRequest
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
logger.HTTPLogger.Print(err)
|
logger.HTTPLogger.Print(err)
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusBadRequest, "Invalid JSON")
|
utils.ErrorResponse(w, http.StatusBadRequest, "Invalid JSON")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err = db.SetColor(id, req.Color)
|
err = db.SetColor(id, req.Color)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.HTTPLogger.Printf("Could not update lamp %d: %s", id, err)
|
logger.HTTPLogger.Printf("Could not update lamp %d: %s", id, err)
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusInternalServerError, err.Error())
|
utils.ErrorResponse(w, http.StatusInternalServerError, err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
updatedState := currentState
|
updatedState := currentState
|
||||||
updatedState.Color = req.Color
|
updatedState.Color = req.Color
|
||||||
updatedState.UpdatedAt = time.Now()
|
updatedState.UpdatedAt = time.Now()
|
||||||
|
utils.SuccessResponse(w, http.StatusOK, updatedState)
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
json.NewEncoder(w).Encode(updatedState)
|
|
||||||
logger.HTTPLogger.Printf("Lamp %d updated to color %s", id, req.Color)
|
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/siestaw/laterna/server/cmd/internal/db"
|
"github.com/siestaw/laterna/server/cmd/internal/db"
|
||||||
"github.com/siestaw/laterna/server/cmd/internal/logger"
|
|
||||||
"github.com/siestaw/laterna/server/cmd/internal/middleware"
|
"github.com/siestaw/laterna/server/cmd/internal/middleware"
|
||||||
"github.com/siestaw/laterna/server/cmd/internal/models"
|
"github.com/siestaw/laterna/server/cmd/internal/models"
|
||||||
"github.com/siestaw/laterna/server/cmd/utils"
|
"github.com/siestaw/laterna/server/cmd/utils"
|
||||||
@@ -20,28 +19,25 @@ func createController(w http.ResponseWriter, r *http.Request) {
|
|||||||
defer r.Body.Close()
|
defer r.Body.Close()
|
||||||
ID, err := db.CreateController()
|
ID, err := db.CreateController()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusInternalServerError, "An error occured. Check the server logs for more information")
|
utils.ErrorResponse(w, http.StatusInternalServerError, "An error occured. Check the server logs for more information")
|
||||||
}
|
}
|
||||||
w.Header().Set("Content-Type", "application/json")
|
utils.SuccessResponse(w, http.StatusOK, models.CreateData{Created: int(ID)})
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
json.NewEncoder(w).Encode(map[string]int64{"ID": ID})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func deleteController(w http.ResponseWriter, r *http.Request) {
|
func deleteController(w http.ResponseWriter, r *http.Request) {
|
||||||
defer r.Body.Close()
|
defer r.Body.Close()
|
||||||
var req models.ControllerRequests
|
var req models.ControllerRequests
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
logger.HTTPLogger.Print(err)
|
utils.ErrorResponse(w, http.StatusBadRequest, "Invalid JSON")
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusBadRequest, "Invalid JSON")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !db.ControllerExists(req.ID) || req.ID <= 0 {
|
if !db.ControllerExists(req.ID) || req.ID <= 0 {
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusBadRequest,"Invalid ID")
|
utils.ErrorResponse(w, http.StatusBadRequest, "Invalid ID")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if db.DeleteController(req.ID) != nil {
|
if db.DeleteController(req.ID) != nil {
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusInternalServerError,"An error occured. Check the server logs for more information")
|
utils.ErrorResponse(w, http.StatusInternalServerError, "An error occured. Check the server logs for more information")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
utils.HTTPResponseHandler(w, r, http.StatusOK, "Success")
|
utils.SuccessResponse(w, http.StatusOK, models.DeleteData{Deleted: req.ID})
|
||||||
}
|
}
|
||||||
+20
-11
@@ -49,16 +49,25 @@ func ValidateToken(providedToken string, storedHash string) bool {
|
|||||||
return err == nil
|
return err == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func HTTPResponseHandler(w http.ResponseWriter, r *http.Request, status int, message string) {
|
func WriteJSONResponse(w http.ResponseWriter, statusCode int, res models.HTTPResponse) {
|
||||||
timestamp := time.Now().Format("2006-01-02_15-04-05")
|
|
||||||
errResp := models.HTTPResponse{
|
|
||||||
Timestamp: timestamp,
|
|
||||||
Status: status,
|
|
||||||
Text: http.StatusText(status),
|
|
||||||
Message: message,
|
|
||||||
Path: r.URL.Path,
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.WriteHeader(status)
|
w.WriteHeader(statusCode)
|
||||||
json.NewEncoder(w).Encode(errResp)
|
|
||||||
|
res.Timestamp = time.Now().UTC().Format(time.RFC3339)
|
||||||
|
|
||||||
|
json.NewEncoder(w).Encode(res)
|
||||||
|
}
|
||||||
|
|
||||||
|
func SuccessResponse(w http.ResponseWriter, statusCode int, data any) {
|
||||||
|
WriteJSONResponse(w, statusCode, models.HTTPResponse{
|
||||||
|
Success: true,
|
||||||
|
Data: data,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func ErrorResponse(w http.ResponseWriter, statusCode int, err string) {
|
||||||
|
WriteJSONResponse(w, statusCode, models.HTTPResponse{
|
||||||
|
Success: false,
|
||||||
|
Error: err,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user