From b88b04a235e34f6f563dfa1da7733ad7e5e066c2 Mon Sep 17 00:00:00 2001 From: Khairul Hidayat Date: Sat, 16 Nov 2024 05:36:54 +0700 Subject: [PATCH] fix: macos fix can't open the app --- server/app/app.go | 14 ++++++++++++-- server/db/database.go | 9 +-------- server/utils/config.go | 25 ++++++++++++++++++++++--- 3 files changed, 35 insertions(+), 13 deletions(-) diff --git a/server/app/app.go b/server/app/app.go index ecc4f34..3146543 100644 --- a/server/app/app.go +++ b/server/app/app.go @@ -1,6 +1,9 @@ package app import ( + "fmt" + "os" + "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" "github.com/joho/godotenv" @@ -13,8 +16,15 @@ import ( func NewApp() *fiber.App { // Load deps utils.CheckAndCreateEnvFile() - godotenv.Load() - db.Init() + godotenv.Load(utils.GetDataPath(".env")) + + dbUrl := os.Getenv("DATABASE_URL") + if dbUrl == "" { + // WAL: _journal_mode=WAL + dbPath := utils.GetDataPath("data.db") + dbUrl = fmt.Sprintf("file:%s?cache=shared&mode=rwc", dbPath) + } + db.Init(dbUrl) // Create fiber app app := fiber.New(fiber.Config{ErrorHandler: ErrorHandler}) diff --git a/server/db/database.go b/server/db/database.go index babe18a..a6125eb 100644 --- a/server/db/database.go +++ b/server/db/database.go @@ -2,7 +2,6 @@ package db import ( "log" - "os" "strings" "gorm.io/driver/postgres" @@ -19,15 +18,9 @@ func Get() *gorm.DB { return dbInstance } -func Init() { +func Init(dsn string) { // log.Println("Initializing database...") - dsn := os.Getenv("DATABASE_URL") - if dsn == "" { - // WAL: _journal_mode=WAL - dsn = "file:data.db?cache=shared&mode=rwc" - } - // Open db connection var con gorm.Dialector if strings.HasPrefix(dsn, "postgres:") { diff --git a/server/utils/config.go b/server/utils/config.go index 600ad05..4a31f21 100644 --- a/server/utils/config.go +++ b/server/utils/config.go @@ -3,13 +3,32 @@ package utils import ( "fmt" "os" + "path/filepath" "rul.sh/vaulterm/server/lib" ) +func GetDataPath(resolveFile string) string { + // Resolve the app directory + execPath, err := os.Executable() + if err != nil { + return "" + } + appDir := filepath.Dir(execPath) + if resolveFile == "" { + return appDir + } + return filepath.Join(appDir, resolveFile) +} + func CheckAndCreateEnvFile() error { + // Skip if ENCRYPTION_KEY is set + if os.Getenv("ENCRYPTION_KEY") != "" { + return nil + } // Check if .env file exists - if _, err := os.Stat(".env"); !os.IsNotExist(err) { + envFile := GetDataPath(".env") + if _, err := os.Stat(envFile); !os.IsNotExist(err) { return nil } @@ -21,11 +40,11 @@ func CheckAndCreateEnvFile() error { // Write the random key to the .env file envContent := fmt.Sprintf("ENCRYPTION_KEY=%s\n", randomKey) - err = os.WriteFile(".env", []byte(envContent), 0644) + err = os.WriteFile(envFile, []byte(envContent), 0644) if err != nil { return err } - fmt.Println(".env file created with ENCRYPTION_KEY.") + fmt.Println(".env file created with ENCRYPTION_KEY.") return nil }