50 lines
1.1 KiB
Go
50 lines
1.1 KiB
Go
package helper
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
type DatabaseConfig struct {
|
|
Host string `yaml:"host" env:"DB_HOST"`
|
|
Port string `yaml:"port" env:"DB_PORT"`
|
|
User string `yaml:"user" env:"DB_USER"`
|
|
Password string `yaml:"password" env:"DB_PASSWORD"`
|
|
Name string `yaml:"name" env:"DB_NAME"`
|
|
}
|
|
|
|
type LoggingConfig struct {
|
|
Level string `yaml:"level" env:"LOG_LEVEL"`
|
|
Encoding string `yaml:"encoding" env:"LOG_ENCODING"`
|
|
}
|
|
|
|
type Config struct {
|
|
Database DatabaseConfig `yaml:"database"`
|
|
Logging LoggingConfig `yaml:"logging"`
|
|
}
|
|
|
|
func LoadConfig(path string) (*Config, error) {
|
|
config := &Config{}
|
|
|
|
// Đọc từ file YAML
|
|
file, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to read config file: %w", err)
|
|
}
|
|
|
|
err = yaml.Unmarshal(file, config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to parse config: %w", err)
|
|
}
|
|
|
|
// Ưu tiên giá trị từ environment variables
|
|
if host := os.Getenv("DB_HOST"); host != "" {
|
|
config.Database.Host = host
|
|
}
|
|
// (Thêm các trường khác tương tự)
|
|
|
|
return config, nil
|
|
}
|