S SmartDocs
Series: Go go 64 lines · Updated 2026-04-18

config.go

Go/payment-gateway-challenge/internal/config/config.go

package config

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

// Config holds environment-driven settings for the gateway process.
type Config struct {
	ServerAddr        string
	DatabaseURL       string
	BankSimulatorURL  string
	AllowedCurrencies []string // len ≤ 3 per assessment brief
	HTTPClientTimeout time.Duration
}

// Load reads configuration from environment variables (after optional godotenv).
func Load() (*Config, error) {
	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		return nil, fmt.Errorf("DATABASE_URL is required")
	}
	bankURL := getenv("BANK_SIMULATOR_URL", "http://localhost:8080/payments")

	rawCur := getenv("ALLOWED_CURRENCIES", "USD,GBP,EUR")
	var cur []string
	for _, c := range strings.Split(rawCur, ",") {
		c = strings.TrimSpace(strings.ToUpper(c))
		if c != "" {
			cur = append(cur, c)
		}
	}
	if len(cur) == 0 {
		return nil, fmt.Errorf("ALLOWED_CURRENCIES must list at least one ISO 4217 code")
	}
	if len(cur) > 3 {
		return nil, fmt.Errorf("assessment requires at most 3 currency codes, got %d", len(cur))
	}

	addr := getenv("SERVER_ADDR", ":8090")
	sec, _ := strconv.Atoi(getenv("HTTP_CLIENT_TIMEOUT_SEC", "15"))
	if sec <= 0 {
		sec = 15
	}
	d := time.Duration(sec) * time.Second

	return &Config{
		ServerAddr:        addr,
		DatabaseURL:       dsn,
		BankSimulatorURL:  bankURL,
		AllowedCurrencies: cur,
		HTTPClientTimeout: d,
	}, nil
}

func getenv(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}

Related articles