cmd/blog_backend/config/config.go
package config
import (
"fmt"
"gorm.io/gorm"
"github.com/spf13/viper"
)
var Config appConfig
type appConfig struct {
// the shared DB ORM object
DB *gorm.DB
// the error thrown be GORM when using DB ORM object
DBErr error
// the path to the error message file. Defaults to "config/errors.yaml"
ErrorFile string `mapstructure:"error_file"`
// the server port. Defaults to 8080
ServerPort int `mapstructure:"server_port"`
// the data source name (DSN) for connecting to the database. required.
DSN string `mapstructure:"dsn"`
// the signing method for JWT. Defaults to "HS256"
JWTSigningMethod string `mapstructure:"jwt_signing_method"`
// JWT signing key. required.
JWTSigningKey string `mapstructure:"jwt_signing_key"`
// JWT verification key. required.
JWTVerificationKey string `mapstructure:"jwt_verification_key"`
// Certificate file for HTTPS
CertFile string `mapstructure:"cert_file"`
// Private key file for HTTPS
KeyFile string `mapstructure:"key_file"`
// MailerLite API Key
APIKey string `mapstructure:"api_key"`
}
func LoadConfig(configPaths ...string) error {
v := viper.New()
v.SetConfigName("server")
v.SetConfigType("yaml")
v.SetEnvPrefix("backend")
v.AutomaticEnv()
v.SetDefault("error_file", "/config/errors.yaml")
v.SetDefault("server_port", 8080)
v.SetDefault("jwt_signing_method", "HS256")
v.SetDefault("cert_file", "/etc/certs/fullchain.pem")
v.SetDefault("key_file", "/etc/certs/privkey.pem")
for _, path := range configPaths {
v.AddConfigPath(path)
}
if err := v.ReadInConfig(); err != nil {
return fmt.Errorf("failed to read the configuration file: %s", err)
}
if err := v.Unmarshal(&Config); err != nil {
return err
}
return nil
}