Files
GoMembership/internal/config/config.go
2024-07-17 16:46:29 +02:00

99 lines
2.3 KiB
Go

package config
import (
"encoding/json"
"os"
"path/filepath"
"github.com/kelseyhightower/envconfig"
"GoMembership/internal/utils"
"GoMembership/pkg/logger"
)
type DatabaseConfig struct {
Path string `json:"Path" envconfig:"DB_PATH"`
}
type AuthenticationConfig struct {
JWTSecret string
CSRFSecret string
APIKEY string `json:"APIKey" envconfig:"API_KEY"`
}
type SMTPConfig struct {
Host string `json:"Host" envconfig:"SMTP_HOST"`
User string `json:"User" envconfig:"SMTP_USER"`
Password string `json:"Password" envconfig:"SMTP_PASS"`
Mailtype string `json:"Mailtype" envconfig:"MAIL_TYPE"`
AdminEmail string `json:"AdminEmail" envconfig:"ADMIN_MAIL"`
Port int `json:"Port" envconfig:"SMTP_PORT"`
}
type TemplateConfig struct {
MailDir string `json:"MailDir" envconfig:"TEMPLATE_DIR"`
}
type Config struct {
Auth AuthenticationConfig `json:"auth"`
DB DatabaseConfig `json:"db"`
Templates TemplateConfig `json:"templates"`
SMTP SMTPConfig `json:"smtp"`
}
var (
CFG Config
Auth AuthenticationConfig
DB DatabaseConfig
Templates TemplateConfig
SMTP SMTPConfig
)
func LoadConfig() {
readFile(&CFG)
readEnv(&CFG)
csrfSecret, err := utils.GenerateRandomString(32)
if err != nil {
logger.Error.Fatalf("could not generate CSRF secret: %v", err)
}
jwtSecret, err := utils.GenerateRandomString(32)
if err != nil {
logger.Error.Fatalf("could not generate JWT secret: %v", err)
}
CFG.Auth.JWTSecret = jwtSecret
CFG.Auth.CSRFSecret = csrfSecret
Auth = CFG.Auth
DB = CFG.DB
Templates = CFG.Templates
SMTP = CFG.SMTP
}
func readFile(cfg *Config) {
path, err := os.Getwd()
if err != nil {
logger.Error.Fatalf("could not get working directory: %v", err)
}
configFile, err := os.Open(filepath.Join(path, "configs", "config.json"))
// configFile, err := os.Open("config.json")
if err != nil {
logger.Error.Fatalf("could not open config file: %v", err)
}
defer configFile.Close()
decoder := json.NewDecoder(configFile)
err = decoder.Decode(cfg)
if err != nil {
logger.Error.Fatalf("could not decode config file: %v", err)
}
}
func readEnv(cfg *Config) {
err := envconfig.Process("", cfg)
if err != nil {
logger.Error.Fatalf("could not decode env variables: %#v", err)
}
}