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