aboutsummaryrefslogtreecommitdiffstats
path: root/backend/internal/config/config.go
blob: f302827c1c8967d6f04ad9a22691bfc0b59b9ec7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package config

import (
	"fmt"
	"os"

	"github.com/joho/godotenv"
)

// Config holds application configuration
type Config struct {
	// Database configuration
	DatabaseDSN string

	// JWT configuration
	JWTSecret string
	JWTExpiry int // in hours

	// Server configuration
	ServerPort int
	ServerHost string

	// Environment (development, staging, production)
	Environment string
}

// LoadConfig loads the application configuration from environment variables
func LoadConfig() (*Config, error) {
	// Load .env file if it exists
	_ = godotenv.Load() // Ignore error if .env file doesn't exist

	// Set defaults and override with environment variables
	config := &Config{
		DatabaseDSN: getEnv("DATABASE_DSN", "postgresql://postgres:postgres@localhost:5432/finance?sslmode=disable"),
		JWTSecret:   getEnv("JWT_SECRET", "supersecretkey"), // This should be changed in production
		JWTExpiry:   getEnvInt("JWT_EXPIRY", 24),            // Default to 24 hours
		ServerPort:  getEnvInt("SERVER_PORT", 8080),         // Default to 8080
		ServerHost:  getEnv("SERVER_HOST", "0.0.0.0"),       // Default to all interfaces
		Environment: getEnv("APP_ENV", "development"),       // Default to development
	}

	return config, nil
}

// getEnv gets an environment variable or returns a default value
func getEnv(key, defaultValue string) string {
	value := os.Getenv(key)
	if value == "" {
		return defaultValue
	}
	return value
}

// getEnvInt gets an environment variable as an integer or returns a default value
func getEnvInt(key string, defaultValue int) int {
	value := os.Getenv(key)
	if value == "" {
		return defaultValue
	}

	intValue, err := parseInt(value)
	if err != nil {
		return defaultValue
	}

	return intValue
}

// parseInt parses a string to an int
func parseInt(value string) (int, error) {
	intValue := 0
	_, err := fmt.Sscanf(value, "%d", &intValue)
	return intValue, err
}