new file structure & koneksi ke DB

This commit is contained in:
mario
2025-05-14 10:23:33 +07:00
parent 8289881df3
commit dd4451c2a8
18 changed files with 753 additions and 243 deletions

View File

@@ -0,0 +1,43 @@
package database
import (
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
// DB is the database instance
var DB *sqlx.DB
// Initialize creates and configures the database connection
func Initialize(dsn string, maxOpenConns, maxIdleConns int, connMaxLifetime time.Duration) error {
var err error
// Connect to the database
DB, err = sqlx.Connect("mysql", dsn)
if err != nil {
return fmt.Errorf("failed to connect to database: %w", err)
}
// Configure connection pool
DB.SetMaxOpenConns(maxOpenConns)
DB.SetMaxIdleConns(maxIdleConns)
DB.SetConnMaxLifetime(connMaxLifetime)
// Check connection
if err := DB.Ping(); err != nil {
return fmt.Errorf("failed to ping database: %w", err)
}
return nil
}
// Close closes the database connection
func Close() error {
if DB != nil {
return DB.Close()
}
return nil
}