Files
go-caatsm/internal/config/config.go
T

122 lines
2.4 KiB
Go
Raw Normal View History

2024-07-19 20:02:18 +08:00
package config
import (
"fmt"
"os"
"regexp"
"strings"
"time"
2024-07-19 20:02:18 +08:00
"github.com/spf13/viper"
)
var MyConfig *Config
type Config struct {
Nats NatsConfig
Subscription SubscriptionConfig
Timeouts TimeoutsConfig
Hasura HasuraConfig
2024-07-19 20:02:18 +08:00
}
type NatsConfig struct {
Client string
URL string
Cluster string
}
type SubscriptionConfig struct {
Topic string `mapstructure:"topic"`
2024-07-19 20:02:18 +08:00
QueueGroup string `mapstructure:"queue_group"`
}
type TimeoutsConfig struct {
2024-07-22 12:42:30 +08:00
Server time.Duration `mapstructure:"server"`
ReconnectWait time.Duration `mapstructure:"reconnect_wait"`
Close time.Duration `mapstructure:"close"`
AckWait time.Duration `mapstructure:"ack_wait"`
2024-07-19 20:02:18 +08:00
}
type BodyConfig struct {
Patterns []PatternConfig
}
type PatternConfig struct {
Pattern string
Comments string
Expression *regexp.Regexp
}
type HasuraConfig struct {
Endpoint string
Secret string
}
const (
2024-07-22 12:42:30 +08:00
EnvProd = "prod"
EnvDev = "dev"
EnvTest = "test"
)
2024-07-19 20:02:18 +08:00
func SetMyConfig(cfg *Config) {
MyConfig = cfg
}
func GetMyConfig() *Config {
if MyConfig == nil {
cfg, err := LoadConfig()
if err != nil {
fmt.Printf("error loading config: %v", err)
2024-07-19 20:02:18 +08:00
}
MyConfig = cfg
}
return MyConfig
}
// LoadConfig loads the configuration from a file
func LoadConfig() (*Config, error) {
// log := utils.Logger
2024-07-19 20:02:18 +08:00
env := os.Getenv("GO_ENV")
if env == "" {
env = "dev"
}
// log.Infof("Environment: %s", env)
2024-07-19 20:02:18 +08:00
viper.SetConfigType("toml")
viper.SetConfigName("config." + env)
viper.AddConfigPath("configs")
viper.SetEnvPrefix("tele")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
if err := viper.ReadInConfig(); err != nil {
errMsg := fmt.Sprintf("error reading config file for environment '%s': %v", env, err)
// log.Error(errMsg)
2024-07-19 20:02:18 +08:00
return nil, fmt.Errorf(errMsg)
}
var config Config
if err := viper.Unmarshal(&config); err != nil {
errMsg := fmt.Sprintf("unable to decode config into struct for environment '%s': %v", env, err)
// log.Error(errMsg)
2024-07-19 20:02:18 +08:00
return nil, fmt.Errorf(errMsg)
}
return &config, nil
}
// ValidateConfig validates the loaded configuration
func ValidateConfig(cfg *Config) error {
// log := utils.Logger
2024-07-19 20:02:18 +08:00
if cfg.Nats.Client == "" {
return fmt.Errorf("nats client is required")
2024-07-19 20:02:18 +08:00
}
if cfg.Nats.URL == "" {
return fmt.Errorf("nats URL is required")
2024-07-19 20:02:18 +08:00
}
if cfg.Subscription.Topic == "" {
return fmt.Errorf("subscription topic is required")
2024-07-19 20:02:18 +08:00
}
// fmt.Println("config validation passed")
2024-07-19 20:02:18 +08:00
return nil
}