feat: implement device management endpoints and database connection

This commit is contained in:
2026-01-04 13:32:57 +01:00
parent 85c336419f
commit 2878d6a59b
2 changed files with 195 additions and 14 deletions
+30 -5
View File
@@ -2,6 +2,7 @@ package main
import (
"context"
"database/sql"
"fmt"
"log"
"net/http"
@@ -11,6 +12,7 @@ import (
"time"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"git.piskot.si/SeminarM2/lambdaiot-core/internal/config"
"git.piskot.si/SeminarM2/lambdaiot-core/internal/handler"
@@ -25,6 +27,20 @@ func main() {
log.Fatalf("failed to load config: %v", err)
}
// connect to database
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true", cfg.Database.User, cfg.Database.Password, cfg.Database.Host, cfg.Database.Port, cfg.Database.Name)
db, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatalf("failed to connect to database: %v", err)
}
defer db.Close()
// test connection
if err := db.Ping(); err != nil {
log.Fatalf("failed to ping database: %v", err)
}
log.Println("connected to database")
// determine address
addr := cfg.Server.Address
if addr == "" {
@@ -69,18 +85,27 @@ func main() {
r.Use(gin.Recovery())
r.Use(middleware.GinLogger())
h := &handler.Handler{DB: db, JWTSecret: cfg.Server.JWTSecret}
// Public routes
r.GET("/health", handler.Health)
r.GET("/hello", handler.Hello)
r.POST("/login", handler.Login)
r.GET("/health", h.Health)
r.GET("/hello", h.Hello)
r.POST("/login", h.Login)
r.GET("/devices", h.GetDevices)
// mqttping endpoint handled by internal/handler
r.POST("/mqttping", handler.MQTTPing)
r.POST("/mqttping", h.MQTTPing)
// Protected routes
auth := r.Group("/")
auth.Use(middleware.AuthMiddleware(cfg.Server.JWTSecret))
auth.GET("/protected", handler.Protected)
auth.GET("/protected", h.Protected)
// Device CRUD routes
auth.POST("/devices", h.CreateDevice)
auth.GET("/devices/:id", h.GetDevice)
auth.PUT("/devices/:id", h.UpdateDevice)
auth.DELETE("/devices/:id", h.DeleteDevice)
srv := &http.Server{
Addr: addr,