mirror of
https://github.com/kaaninchen/Laterna.git
synced 2026-09-17 11:02:47 +00:00
database setup and getcurrent
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
package db
|
||||
+23
-12
@@ -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) {
|
||||
|
||||
}
|
||||
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user