Chuỗi bài: Go
go
64 dòng
· Cập nhật 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
}
Bài viết liên quan
Go
go
Cập nhật 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/hashpw/main.go).
Đọc bài viết →
Go
go
Cập nhật 2026-04-18
main.go
main.go — go source code from the Go learning materials (Go/Baasid/cmd/server/main.go).
Đọc bài viết →
Go
go
Cập nhật 2026-04-18
docs.go
docs.go — go source code from the Go learning materials (Go/Baasid/docs/docs.go).
Đọc bài viết →
Go
go
Cập nhật 2026-04-18
jwt.go
jwt.go — go source code from the Go learning materials (Go/Baasid/internal/auth/jwt.go).
Đọc bài viết →
Go
go
Cập nhật 2026-04-18
password.go
password.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password.go).
Đọc bài viết →
Go
go
Cập nhật 2026-04-18
password_test.go
password_test.go — go source code from the Go learning materials (Go/Baasid/internal/auth/password_test.go).
Đọc bài viết →