update configuration to include database connection settings and adjust connection management
This commit is contained in:
@@ -1,4 +1,12 @@
|
||||
# Server Settings
|
||||
PORT=8080
|
||||
|
||||
# DB Settings
|
||||
DB_DSN=root:secret@tcp(127.0.0.1:3306)/emly?parseTime=true&loc=UTC
|
||||
MAX_OPEN_CONNS=25
|
||||
MAX_IDLE_CONNS=5
|
||||
CONN_MAX_LIFETIME=5m
|
||||
|
||||
# API Keys
|
||||
API_KEY=key-one
|
||||
ADMIN_KEY=admin-key-one
|
||||
|
||||
@@ -2,6 +2,7 @@ package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -10,6 +11,9 @@ type Config struct {
|
||||
DSN string
|
||||
APIKey string
|
||||
AdminKey string
|
||||
MaxOpenConns int
|
||||
MaxIdleConns int
|
||||
ConnMaxLifetime int
|
||||
}
|
||||
|
||||
func Load() *Config {
|
||||
@@ -38,10 +42,26 @@ func Load() *Config {
|
||||
}
|
||||
}
|
||||
|
||||
maxOpenConns, err := strconv.Atoi(os.Getenv("DB_MAX_OPEN_CONNS"))
|
||||
if err != nil {
|
||||
maxOpenConns = 30
|
||||
}
|
||||
maxIdleConns, err := strconv.Atoi(os.Getenv("DB_MAX_IDLE_CONNS"))
|
||||
if err != nil {
|
||||
maxIdleConns = 5
|
||||
}
|
||||
connMaxLifetime, err := strconv.Atoi(os.Getenv("DB_CONN_MAX_LIFETIME"))
|
||||
if err != nil {
|
||||
connMaxLifetime = 5
|
||||
}
|
||||
|
||||
return &Config{
|
||||
Port: port,
|
||||
DSN: os.Getenv("DB_DSN"),
|
||||
APIKey: apiKey,
|
||||
AdminKey: adminKey,
|
||||
MaxOpenConns: maxOpenConns,
|
||||
MaxIdleConns: maxIdleConns,
|
||||
ConnMaxLifetime: connMaxLifetime,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,9 +15,9 @@ func Connect(cfg *config.Config) (*sqlx.DB, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
db.SetMaxOpenConns(25)
|
||||
db.SetMaxIdleConns(5)
|
||||
db.SetConnMaxLifetime(5 * time.Minute)
|
||||
db.SetMaxOpenConns(cfg.MaxOpenConns)
|
||||
db.SetMaxIdleConns(cfg.MaxIdleConns)
|
||||
db.SetConnMaxLifetime(time.Duration(cfg.ConnMaxLifetime) * time.Minute)
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user