internal/curd.go
68 lines · 1875 bytes
1package internal
2
3import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "runtime"
8 "strings"
9 "time"
10)
11
12func GetTokenFromFile(filePath string) (string, error) {
13 // Read the token from the file
14 data, err := os.ReadFile(filePath)
15 if err != nil {
16 return "", fmt.Errorf("failed to read token from file: %w", err)
17 }
18
19 // Convert the byte slice to a string and remove any surrounding whitespace or newlines
20 token := strings.TrimSpace(string(data))
21
22 return token, nil
23}
24
25// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
26func Log(data interface{}, logFile string) error {
27 // Open or create the log file
28 file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
29 if err != nil {
30 return err
31 }
32 defer file.Close() // Ensure the file is closed when done
33
34 // Attempt to marshal the data into JSON
35 jsonData, err := json.Marshal(data)
36 if err != nil {
37 return err
38 }
39
40 // Get the caller information
41 _, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
42 if !ok {
43 return fmt.Errorf("unable to get caller information")
44 }
45
46 // Log the current time and the JSON representation along with caller info
47 currentTime := time.Now().Format("2006/01/02 15:04:05")
48 logMessage := fmt.Sprintf("[LOG] %s %s %d: %s\n", currentTime, filename, lineNumber, jsonData)
49 _, err = fmt.Fprint(file, logMessage) // Write to the file
50 if err != nil {
51 return err
52 }
53
54 return nil
55}
56
57
58// ClearScreen clears the terminal screen and saves the state
59func ClearScreen() {
60 fmt.Print("\033[?1049h") // Switch to alternate screen buffer
61 fmt.Print("\033[2J") // Clear the entire screen
62 fmt.Print("\033[H") // Move cursor to the top left
63}
64
65// RestoreScreen restores the original terminal state
66func RestoreScreen() {
67 fmt.Print("\033[?1049l") // Switch back to the main screen buffer
68}