From 5281f731485c22107370d6a5595ec4d8267c8479 Mon Sep 17 00:00:00 2001 From: Mitsu <124433727+Mizuw@users.noreply.github.com> Date: Tue, 8 Jul 2025 22:03:03 +0200 Subject: [PATCH] database setup and getcurrent --- cmd/internal/config/config.go | 19 +++++-------------- cmd/internal/db/connection.go | 24 +++++++++++++++++++++--- cmd/internal/db/queries.go | 19 +++++++++++++++++++ cmd/internal/db/utils.go | 1 - cmd/internal/http/server.go | 35 +++++++++++++++++++++++------------ cmd/internal/models/models.go | 28 ++++++++++++++++++++++++++++ cmd/utils/utils.go | 23 +++++++++++++++++++++++ 7 files changed, 119 insertions(+), 30 deletions(-) create mode 100644 cmd/internal/db/queries.go delete mode 100644 cmd/internal/db/utils.go create mode 100644 cmd/internal/models/models.go create mode 100644 cmd/utils/utils.go diff --git a/cmd/internal/config/config.go b/cmd/internal/config/config.go index c83ea44..355175d 100644 --- a/cmd/internal/config/config.go +++ b/cmd/internal/config/config.go @@ -4,27 +4,18 @@ import ( "encoding/json" "fmt" "os" + + "github.com/siestaw/laterna/server/cmd/internal/models" ) -type HTTPConfig struct { - AdminToken string `json:"adminToken"` - Port int `json:"port"` -} - -type Config struct { - HTTP HTTPConfig `json:"http"` - FileLogging bool `json:"fileLogging"` - VerboseLogging bool `json:"verboseLogging"` -} - -func LoadConfig(path string) *Config { +func LoadConfig(path string) *models.Config { file, err := os.ReadFile(path) if err != nil { fmt.Println("An error occured while reading the config file:", err) os.Exit(1) } - var cfg Config + var cfg models.Config err = json.Unmarshal(file, &cfg) if err != nil { fmt.Println("An error occured while parsing the config file:", err) @@ -34,4 +25,4 @@ func LoadConfig(path string) *Config { return &cfg } -var AppConfig *Config +var AppConfig *models.Config diff --git a/cmd/internal/db/connection.go b/cmd/internal/db/connection.go index 2d09db7..41a632d 100644 --- a/cmd/internal/db/connection.go +++ b/cmd/internal/db/connection.go @@ -7,11 +7,29 @@ import ( "github.com/siestaw/laterna/server/cmd/internal/logger" ) +var DB *sql.DB + func ConnectDB() { - db, err := sql.Open("sqlite3", "./db.sql") + var err error + DB, err = sql.Open("sqlite3", "./db.sql") if err != nil { logger.DBLogger.Printf("An Error occured while connecting to the database: %v", err) + return + } + logger.DBLogger.Printf("Successfully connected to the database!") + InitDB() +} + +func InitDB() { + _, err := DB.Exec(` + CREATE TABLE IF NOT EXISTS lamp_state ( + id TEXT PRIMARY KEY, + color TEXT NOT NULL, + updated_at DATETIME NOT NULL + ); + `) + + if err != nil { + logger.DBLogger.Fatalf("An error occured while initializing the database: %v", err) } - logger.DBLogger.Printf("Connected") - defer db.Close() } diff --git a/cmd/internal/db/queries.go b/cmd/internal/db/queries.go new file mode 100644 index 0000000..bd032dc --- /dev/null +++ b/cmd/internal/db/queries.go @@ -0,0 +1,19 @@ +package db + +import ( + "github.com/siestaw/laterna/server/cmd/internal/logger" + "github.com/siestaw/laterna/server/cmd/internal/models" +) + +func ViewColor(id int) (*models.LampState, error) { + row := DB.QueryRow("SELECT * FROM lamp_state WHERE id = ?", id) + + var state models.LampState + err := row.Scan(&state.ID, &state.Color, &state.UpdatedAt) + if err != nil { + logger.DBLogger.Print(err) + return nil, err + } + + return &state, nil +} diff --git a/cmd/internal/db/utils.go b/cmd/internal/db/utils.go deleted file mode 100644 index 3a49c63..0000000 --- a/cmd/internal/db/utils.go +++ /dev/null @@ -1 +0,0 @@ -package db diff --git a/cmd/internal/http/server.go b/cmd/internal/http/server.go index 95b1e47..108268b 100644 --- a/cmd/internal/http/server.go +++ b/cmd/internal/http/server.go @@ -1,35 +1,46 @@ package http import ( + "encoding/json" "fmt" "net/http" + "strconv" "github.com/siestaw/laterna/server/cmd/internal/config" + "github.com/siestaw/laterna/server/cmd/internal/db" "github.com/siestaw/laterna/server/cmd/internal/logger" + "github.com/siestaw/laterna/server/cmd/utils" ) func StartHTTPServer() { router := http.NewServeMux() - router.HandleFunc("GET /api/v1/admin/token/new", createToken) + router.HandleFunc("GET /api/v1/id/{ID}", getCurrent) + router.HandleFunc("POST /api/v1/id/{ID}", setCurrent) port := config.AppConfig.HTTP.Port logger.HTTPLogger.Printf("HTTP Server running on :%v", port) http.ListenAndServe(fmt.Sprintf(":%d", port), router) } -func createToken(w http.ResponseWriter, r *http.Request) { // temporary, only for testing - authHeader := r.Header.Get("Authorization") - adminToken := config.AppConfig.HTTP.AdminToken +func getCurrent(w http.ResponseWriter, r *http.Request) { + idStr := r.PathValue("ID") + id, err := strconv.Atoi(idStr) + if err != nil { + utils.HTTPErrorHandling(w, r, http.StatusBadRequest, "Invalid ID") + return + } - if authHeader == "" { - http.Error(w, "Authorization header missing", http.StatusUnauthorized) + state, err := db.ViewColor(id) + if err != nil { + utils.HTTPErrorHandling(w, r, http.StatusBadRequest, "Lamp not found") return } - if authHeader != adminToken { - http.Error(w, "nuh uh", http.StatusUnauthorized) - return - } - print(authHeader) - fmt.Fprintf(w, "Success!!! Token: %v, authHeader: %v", adminToken, authHeader) + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(state) +} + +func setCurrent(w http.ResponseWriter, r *http.Request) { + } diff --git a/cmd/internal/models/models.go b/cmd/internal/models/models.go new file mode 100644 index 0000000..e83152f --- /dev/null +++ b/cmd/internal/models/models.go @@ -0,0 +1,28 @@ +package models + +import "time" + +type HTTPConfig struct { + AdminToken string `json:"adminToken"` + Port int `json:"port"` +} + +type Config struct { + HTTP HTTPConfig `json:"http"` + FileLogging bool `json:"fileLogging"` + VerboseLogging bool `json:"verboseLogging"` +} + +type HTTPError struct { + Timestamp string `json:"timestamp"` + Status int `json:"status"` + Error string `json:"error"` + Message string `json:"message"` + Path string `json:"path"` +} + +type LampState struct { + ID int `json:"id"` + Color string `json:"color"` + UpdatedAt time.Time `json:"updated_at"` +} diff --git a/cmd/utils/utils.go b/cmd/utils/utils.go new file mode 100644 index 0000000..eb1586d --- /dev/null +++ b/cmd/utils/utils.go @@ -0,0 +1,23 @@ +package utils + +import ( + "encoding/json" + "net/http" + "time" + + "github.com/siestaw/laterna/server/cmd/internal/models" +) + +func HTTPErrorHandling(w http.ResponseWriter, r *http.Request, status int, message string) { + timestamp := time.Now().Format("2006-01-02_15-04-05") + errResp := models.HTTPError{ + Timestamp: timestamp, + Status: status, + Error: http.StatusText(status), + Message: message, + Path: r.URL.Path, + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + json.NewEncoder(w).Encode(errResp) +}