Backend/pkg/helpers/config/config.go
2024-12-06 21:53:09 +01:00

84 lines
2.4 KiB
Go
Executable file

/*
ScheduleTogether Backend
Copyright (C) 2024, Zervó Zadachin
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License version 3 for more details.
This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package config
import (
"fmt"
"os"
"strconv"
"git.zervo.org/scheduletogether/backend/pkg/types"
)
// Required environment variables
var requiredEnvVars = []string{
"DATABASE_URL",
"DATABASE_DIALECT",
"JWT_SECRET",
// Add other required environment variables here
}
// LoadConfig reads configuration values from environment variables
func LoadConfig() (*types.Config, error) {
// Check if all required environment variables are set
for _, envVar := range requiredEnvVars {
if os.Getenv(envVar) == "" {
return nil, fmt.Errorf("required environment variable %s is not set", envVar)
}
}
// Load configuration values
cfg := &types.Config{
ServerPort: getEnvInt("SERVER_PORT", 8080),
DatabaseDialect: os.Getenv("DATABASE_DIALECT"),
DatabaseURL: os.Getenv("DATABASE_URL"),
DatabaseDebug: getEnvBool("DATABASE_DEBUG", false),
JWTSecret: os.Getenv("JWT_SECRET"),
JWTExpiration: getEnvInt("JWT_EXPIRATION", 15),
}
// Return config object
return cfg, nil
}
// getEnvInt returns an int from an environment variable, or a default value if it is not set or invalid
func getEnvInt(key string, def int) int {
if v := os.Getenv(key); v != "" {
if i, err := strconv.Atoi(v); err == nil {
return i
}
}
return def
}
// getEnvBool returns a bool from an environment variable, or a default value if it is not set or invalid
func getEnvBool(key string, def bool) bool {
if v := os.Getenv(key); v != "" {
if b, err := strconv.ParseBool(v); err == nil {
return b
}
}
return def
}