package env import ( "bufio" "os" "strings" "github.com/dmitriygnatenko/internal/interfaces" ) // nolint:gosec const ( envPathVar = "ENV_PATH" envPath = "../../config/.env" appPortEnv = "APP_PORT" dbHostEnv = "DB_HOST" dbPortEnv = "DB_PORT" dbNameEnv = "DB_NAME" dbUserEnv = "DB_USER" dbPasswordEnv = "DB_PASSWORD" smtpHostEnv = "SMTP_HOST" smtpPortEnv = "SMTP_PORT" smtpUserEnv = "SMTP_USER" smtpPasswordEnv = "SMTP_PASSWORD" staticVersionEnv = "STATIC_VERSION" gaEnabledEnv = "GA_ENABLED" adminEmailEnv = "ADMIN_EMAIL" adminUserEnv = "ADMIN_USER" adminPasswordEnv = "ADMIN_PASSWORD" ) type env struct { appPort string dbHost string dbPort string dbName string dbUser string dbPassword string smtpHost string smtpPort string smtpUser string smtpPassword string staticVersion string gaEnabled bool adminEmail string adminUser string adminPassword string } func Init() (interfaces.IEnv, error) { res := &env{} path := os.Getenv(envPathVar) if path == "" { path = envPath } file, err := os.Open(envPath) if err != nil { return nil, err } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) if line == "" { continue } if strings.HasPrefix(line, "#") { continue } parts := strings.Split(line, "=") if len(parts) < 2 { continue } set(res, parts[0], parts[1]) } if err = scanner.Err(); err != nil { return nil, err } return res, err } func set(res *env, key string, value string) { switch key { case appPortEnv: res.appPort = value case dbHostEnv: res.dbHost = value case dbPortEnv: res.dbPort = value case dbNameEnv: res.dbName = value case dbUserEnv: res.dbUser = value case dbPasswordEnv: res.dbPassword = value case smtpPortEnv: res.smtpPort = value case smtpHostEnv: res.smtpHost = value case smtpUserEnv: res.smtpUser = value case smtpPasswordEnv: res.smtpPassword = value case staticVersionEnv: res.staticVersion = value case gaEnabledEnv: res.gaEnabled = value == "true" case adminEmailEnv: res.adminEmail = value case adminUserEnv: res.adminUser = value case adminPasswordEnv: res.adminPassword = value } } func (e *env) GetAppPort() string { return e.appPort } func (e *env) GetDBHost() string { return e.dbHost } func (e *env) GetDBPort() string { return e.dbPort } func (e *env) GetDBName() string { return e.dbName } func (e *env) GetDBUser() string { return e.dbUser } func (e *env) GetDBPassword() string { return e.dbPassword } func (e *env) GetSMTPPort() string { return e.smtpPort } func (e *env) GetSMTPHost() string { return e.smtpHost } func (e *env) GetSMTPUser() string { return e.smtpUser } func (e *env) GetSMTPPassword() string { return e.smtpPassword } func (e *env) GetStaticVersion() string { return e.staticVersion } func (e *env) IsGAEnabled() bool { return e.gaEnabled } func (e *env) GetAdminEmail() string { return e.adminEmail } func (e *env) GetAdminUser() string { return e.adminUser } func (e *env) GetAdminPassword() string { return e.adminPassword }