-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (78 loc) · 2.18 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"github.com/djian01/nt/pkg/cmd/root" // import root pkg
)
// create a global logFile pointer and logger pointer
var (
logFile *os.File
logger *log.Logger
)
// Func: get the config file path for different OS
func getConfigFilePath(appName string) (string, error) {
var configDir string
var err error
if runtime.GOOS == "darwin" {
// macOS: ~/Library/Application Support/<appName> (/Users/<User Name>/Library/Application Support/<appName>)
configDir, err = os.UserConfigDir()
if err != nil {
return "", err
}
configDir = filepath.Join(configDir, appName)
} else {
// Windows/Linux: directory where executable resides
exePath, err := os.Executable()
if err != nil {
return "", err
}
configDir = filepath.Dir(exePath)
}
// Ensure the config directory exists
if err := os.MkdirAll(configDir, os.ModePerm); err != nil {
return "", err
}
// Return full path for config file
return configDir, nil
}
func main() {
// get the config file path
// macOS: ~/Library/Application Support/<appName>
// Windows & Linux: the config file path is the same as the executable path
configPath, err := getConfigFilePath("nt")
if err != nil {
log.Fatal("Failed to get log file path:", err)
return
}
// create or open the output.txt file for logging
// "os.O_RDWR": open file to read and write
// "os.O_CREATE": Create the file with the mode permissions if file does not exist. Cursor is at the beginning.
// "os.O_APPEND": Only allow write past end of file
logFile, err := os.OpenFile(filepath.Join(configPath, "nt.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatal("Error opening log file: ", err)
return
}
defer logFile.Close()
// create a new logger
logger = log.New(logFile, "", log.LstdFlags)
//// defer func() to capture the panic & debug stack messages
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
logger.Printf("Recovered panic: %v", r)
stack := debug.Stack()
logger.Printf("Stack Trace: %v", string(stack))
}
}()
// call the rootCmd
rootCmd := root.RootCommand()
err = rootCmd.Execute()
if err != nil {
panic(err)
}
}