Files
egutierrez ebf246beb0 feat(infra): funciones impuras Go para carga de env/config (dotenv, env_require, config_from_env, config_from_file)
- dotenv_load: parser .env con no-sobreescritura y soporte de comillas
- env_require: os.Getenv con error descriptivo fail-fast
- env_require_all: verifica multiples vars y lista todas las faltantes
- config_from_env: reflection sobre struct tags env/default/required/secret, 5 tipos soportados
- config_from_file: JSON via stdlib, YAML stub con not-implemented
- 25 tests unitarios, todos PASS

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 02:01:50 +02:00

41 lines
1.2 KiB
Go

package infra
import (
"encoding/json"
"fmt"
"os"
"strings"
)
// ConfigFromFile loads configuration from a file into target.
// The target must be a non-nil pointer to a struct (same as json.Unmarshal).
//
// Supported formats:
// - JSON (.json) — full support via encoding/json
// - YAML (.yaml, .yml) — stub: returns "not implemented"
//
// The format is determined by the file extension (case-insensitive).
func ConfigFromFile(path string, target any) error {
lower := strings.ToLower(path)
switch {
case strings.HasSuffix(lower, ".json"):
return loadJSON(path, target)
case strings.HasSuffix(lower, ".yaml"), strings.HasSuffix(lower, ".yml"):
return fmt.Errorf("config_from_file: YAML support not implemented; use a JSON file or add gopkg.in/yaml.v3")
default:
return fmt.Errorf("config_from_file: unsupported file extension for %q (supported: .json, .yaml, .yml)", path)
}
}
func loadJSON(path string, target any) error {
data, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("config_from_file: read %q: %w", path, err)
}
if err := json.Unmarshal(data, target); err != nil {
return fmt.Errorf("config_from_file: parse JSON %q: %w", path, err)
}
return nil
}