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