77 lines
1.5 KiB
Go
77 lines
1.5 KiB
Go
package config
|
|
|
|
import (
|
|
"log"
|
|
"os"
|
|
"strconv"
|
|
)
|
|
|
|
type Config struct {
|
|
Server ServerConfig
|
|
Database DatabaseConfig
|
|
}
|
|
|
|
type ServerConfig struct {
|
|
Port int
|
|
Mode string
|
|
}
|
|
|
|
type DatabaseConfig struct {
|
|
Host string
|
|
Port int
|
|
Username string
|
|
Password string
|
|
Database string
|
|
Schema string
|
|
}
|
|
|
|
func LoadConfig() *Config {
|
|
config := &Config{
|
|
Server: ServerConfig{
|
|
Port: getEnvAsInt("PORT", 8080),
|
|
Mode: getEnv("GIN_MODE", "debug"),
|
|
},
|
|
Database: DatabaseConfig{
|
|
Host: getEnv("BLUEPRINT_DB_HOST", "localhost"),
|
|
Port: getEnvAsInt("BLUEPRINT_DB_PORT", 5432),
|
|
Username: getEnv("BLUEPRINT_DB_USERNAME", "postgres"),
|
|
Password: getEnv("BLUEPRINT_DB_PASSWORD", "postgres"),
|
|
Database: getEnv("BLUEPRINT_DB_DATABASE", "api_service"),
|
|
Schema: getEnv("BLUEPRINT_DB_SCHEMA", "public"),
|
|
},
|
|
}
|
|
|
|
return config
|
|
}
|
|
|
|
func getEnv(key, defaultValue string) string {
|
|
if value := os.Getenv(key); value != "" {
|
|
return value
|
|
}
|
|
return defaultValue
|
|
}
|
|
|
|
func getEnvAsInt(key string, defaultValue int) int {
|
|
valueStr := getEnv(key, "")
|
|
if value, err := strconv.Atoi(valueStr); err == nil {
|
|
return value
|
|
}
|
|
return defaultValue
|
|
}
|
|
|
|
func (c *Config) Validate() error {
|
|
if c.Database.Host == "" {
|
|
log.Fatal("Database host is required")
|
|
}
|
|
if c.Database.Username == "" {
|
|
log.Fatal("Database username is required")
|
|
}
|
|
if c.Database.Password == "" {
|
|
log.Fatal("Database password is required")
|
|
}
|
|
if c.Database.Database == "" {
|
|
log.Fatal("Database name is required")
|
|
}
|
|
return nil
|
|
}
|