fix: macos fix can't open the app

This commit is contained in:
Khairul Hidayat 2024-11-16 05:36:54 +07:00
parent ad8b67ccd3
commit b88b04a235
3 changed files with 35 additions and 13 deletions

View File

@ -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})

View File

@ -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:") {

View File

@ -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
}