CCTV/config/env.go

85 lines
1.5 KiB
Go

package config
import (
"bufio"
"os"
"strings"
"git.neunzweinull.com/jan/CCTV/internal"
)
const (
Prefix = "CCTV_"
)
func LoadEnv() error {
// TODO: Load env from custom file
setDefaultEnvs()
file, err := os.Open(".env")
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.Split(scanner.Text(), "=")
//Ignore empty lines and comments
if len(line) < 2 || strings.HasPrefix(line[0], "#") {
continue
}
key := strings.TrimSpace(line[0])
value := strings.TrimSpace(line[1])
if key == "" || value == "" {
continue
}
// Add prefix
key = Prefix + key
// Remove quotes
value = strings.Trim(value, `"'`)
os.Setenv(key, value)
internal.SetShit()
}
return scanner.Err()
}
func requiredEnvs() {
if _, ok := os.LookupEnv(Prefix + "BearerToken"); !ok {
panic("BearerToken is required")
}
if _, ok := os.LookupEnv(Prefix + "UploadDir"); !ok {
panic("UploadDir is required")
}
if _, ok := os.LookupEnv(Prefix + "JWT_Secret"); !ok {
panic("JWT_Secret is required")
}
}
func setDefaultEnvs() {
if _, ok := os.LookupEnv(Prefix + "UploadDir"); !ok {
os.Setenv(Prefix+"UploadDir", "uploads/")
}
if _, ok := os.LookupEnv(Prefix + "LOG_FILE"); !ok {
os.Setenv(Prefix+"LOG_FILE", "auth_failures.log")
}
if _, ok := os.LookupEnv(Prefix + "MaxFailedAttempts"); !ok {
os.Setenv(Prefix+"MaxFailedAttempts", "3")
}
if _, ok := os.LookupEnv(Prefix + "BanDuration"); !ok {
os.Setenv(Prefix+"BanDuration", "5")
}
}