Files
easywish/backend/config/config.go

93 lines
2.4 KiB
Go

package config
import (
"log"
"reflect"
"fmt"
"github.com/spf13/viper"
)
type Config struct {
Hostname string `mapstructure:"HOSTNAME"`
Port string `mapstructure:"PORT"`
DatabaseUrl string `mapstructure:"DATABASE_URL"`
RedisUrl string `mapstructure:"REDIS_URL"`
MinioUrl string `mapstructure:"MINIO_URL"`
JwtAlgorithm string `mapstructure:"JWT_ALGORITHM"`
JwtSecret string `mapstructure:"JWT_SECRET"`
JwtIssuer string `mapstructure:"JWT_ISSUER"`
JwtAudience string `mapstructure:"JWT_AUDIENCE"`
JwtExpAccess string `mapstructure:"JWT_EXP_ACCESS"`
JwtExpRefresh string `mapstructure:"JWT_EXP_REFRESH"`
Environment string `mapstructure:"ENVIRONMENT"`
}
var config *Config
// TODO: migrate logging to Zap
func LoadConfig() error {
// Load .env file
if err := viper.ReadInConfig(); err != nil {
log.Printf("Error reading config file, proceeding with environment variables. %s", err)
}
// Set default parameters
viper.SetDefault("HOSTNAME", "localhost")
viper.SetDefault("PORT", "8080")
viper.SetDefault("DATABASE_URL", "mydb")
viper.SetDefault("REDIS_URL", "myredis")
viper.SetDefault("MINIO_URL", "myminio")
viper.SetDefault("JWT_ALGORITHM", "HS256")
viper.SetDefault("JWT_SECRET", "default_jwt_secret_please_change") // TODO: remove and randomly generate
viper.SetDefault("JWT_EXP_ACCESS", "5m")
viper.SetDefault("JWT_EXP_REFRESH", "1w")
viper.SetDefault("JWT_AUDIENCE", "easywish")
viper.SetDefault("JWT_ISSUER", "easywish")
viper.SetDefault("ENVIRONMENT", "production")
// Set the file name and type for Viper
viper.SetConfigName(".env") // name of config file (without extension)
viper.SetConfigType("env") // REQUIRED if the config file does not have the extension
viper.AddConfigPath(".") // optionally look for config in the working directory
// Unmarshal the configuration into the Config struct
if err := viper.Unmarshal(&config); err != nil {
log.Fatalf("Unable to decode into struct, %v", err)
}
// Perform validation
if err := validateConfig(); err != nil {
return err
}
return nil
}
func validateConfig() error {
v := reflect.ValueOf(*config)
t := v.Type()
for i := range v.NumField() {
field := v.Field(i)
fieldType := t.Field(i)
// Check if the field is a string and is empty
if field.Kind() == reflect.String && field.String() == "" {
return fmt.Errorf("Missing required configuration: %s", fieldType.Name)
}
}
return nil
}
func GetConfig() *Config {
return config
}