S SmartDocs
Série: Go go 65 lignes · Mis à jour 2026-04-18

config.go

Go/Baasid/internal/config/config.go

// Package config loads application configuration from environment variables.
//
// We centralise all tunables here so cmd/server and tests can share the same
// parsing logic. Values are validated at startup to fail fast instead of
// returning cryptic database errors at runtime.
package config

import (
	"fmt"
	"os"
	"strconv"
	"time"
)

// Config holds every runtime setting the Baasid HTTP server needs.
type Config struct {
	// ServerAddr is the TCP address Echo listens on, e.g. ":8080".
	ServerAddr string

	// DatabaseURL is the full PostgreSQL DSN consumed by GORM / pgx.
	// Example: postgres://user:pass@localhost:5432/baasid?sslmode=disable
	DatabaseURL string

	// JWTSecret is the symmetric key used to sign and verify HS256 tokens.
	// MUST be long and random in production (never commit real secrets).
	JWTSecret string

	// JWTExpiry is how long an access token remains valid after login.
	JWTExpiry time.Duration
}

// Load reads environment variables (optionally prefixed) and returns Config.
// godotenv is invoked from main so this package stays pure and easy to test.
func Load() (*Config, error) {
	addr := getenv("SERVER_ADDR", ":8080")
	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		return nil, fmt.Errorf("DATABASE_URL is required (PostgreSQL connection string)")
	}
	secret := os.Getenv("JWT_SECRET")
	if secret == "" {
		return nil, fmt.Errorf("JWT_SECRET is required (use a long random string in production)")
	}

	expStr := getenv("JWT_EXPIRY_MINUTES", "60")
	expMin, err := strconv.Atoi(expStr)
	if err != nil || expMin <= 0 {
		return nil, fmt.Errorf("JWT_EXPIRY_MINUTES must be a positive integer, got %q", expStr)
	}

	return &Config{
		ServerAddr:   addr,
		DatabaseURL:  dsn,
		JWTSecret:    secret,
		JWTExpiry:    time.Duration(expMin) * time.Minute,
	}, nil
}

// getenv returns os.Getenv(key) if set, otherwise defaultVal.
func getenv(key, defaultVal string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return defaultVal
}

Articles liés