52 lines
1.2 KiB
Go
52 lines
1.2 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"os"
|
||
|
)
|
||
|
|
||
|
type PersistentData struct {
|
||
|
QuestradeRefreshToken string `json:"questradeRefreshToken"`
|
||
|
}
|
||
|
|
||
|
func loadPersistentData() (*PersistentData, error) {
|
||
|
persistentData := &PersistentData{}
|
||
|
|
||
|
f, err := os.Open("data/persistentData.json")
|
||
|
if errors.Is(err, os.ErrNotExist) {
|
||
|
// handle the case where the file doesn't exist
|
||
|
persistentData.QuestradeRefreshToken = os.Getenv("questrade_refresh_token")
|
||
|
return persistentData, nil
|
||
|
}
|
||
|
|
||
|
defer f.Close()
|
||
|
|
||
|
b, err := io.ReadAll(f)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("failed to read file data/persistentData.json: %v", err)
|
||
|
}
|
||
|
|
||
|
err = json.Unmarshal(b, persistentData)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("failed to unmarshal data/persistentData.json to PersistentData struct: %v", err)
|
||
|
}
|
||
|
|
||
|
return persistentData, nil
|
||
|
|
||
|
}
|
||
|
|
||
|
func savePersistentData(PersistentData) error {
|
||
|
b, err := json.Marshal(persistentData)
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("failed to marshal persistentData to bytes: %v", err)
|
||
|
}
|
||
|
err = os.WriteFile("data/persistentData.json", b, 0644)
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("failed to write file data/persistentData.json: %v", err)
|
||
|
}
|
||
|
return nil
|
||
|
}
|