
This commit adds a complete Go implementation of the Todo application. The application uses Gin framework for the web server, GORM for database access, and SQLite for storage. Key features: - Todo CRUD operations with the same API endpoints - Health check endpoint - Database migrations - Tests for models, services, and API handlers - Documentation for the API - Configurable settings
48 lines
1.1 KiB
Go
48 lines
1.1 KiB
Go
package database
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
|
|
"github.com/simpletodoapp/go-todo-app/internal/config"
|
|
"github.com/simpletodoapp/go-todo-app/internal/model"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
// Database holds the database connection
|
|
type Database struct {
|
|
DB *gorm.DB
|
|
}
|
|
|
|
// NewDatabase initializes a new database connection
|
|
func NewDatabase(cfg *config.Config) (*Database, error) {
|
|
// Configure GORM
|
|
gormConfig := &gorm.Config{
|
|
Logger: logger.Default.LogMode(logger.Info),
|
|
}
|
|
|
|
// Connect to SQLite database
|
|
log.Printf("Connecting to database: %s", cfg.GetDatabaseURL())
|
|
db, err := gorm.Open(sqlite.Open(cfg.GetDatabaseURL()), gormConfig)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to connect to database: %v", err)
|
|
}
|
|
|
|
// Auto-migrate the schema
|
|
if err := db.AutoMigrate(&model.Todo{}); err != nil {
|
|
return nil, fmt.Errorf("failed to migrate database: %v", err)
|
|
}
|
|
|
|
return &Database{DB: db}, nil
|
|
}
|
|
|
|
// Health checks the database connection
|
|
func (d *Database) Health() error {
|
|
sqlDB, err := d.DB.DB()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return sqlDB.Ping()
|
|
} |