Compare commits
2 Commits
0ca262c2ea
...
796075d9f2
Author | SHA1 | Date | |
---|---|---|---|
796075d9f2 | |||
1874a875f5 |
@ -14,12 +14,22 @@ type Record struct {
|
||||
|
||||
// AppContext is the application data store that holds Records
|
||||
type AppContext struct {
|
||||
Records []Record
|
||||
Records []Record
|
||||
dataPath string
|
||||
}
|
||||
|
||||
func NewContext(dataPath string) (AppContext, error) {
|
||||
ctx := AppContext{dataPath: dataPath}
|
||||
err := ctx.LoadRecords()
|
||||
if err != nil {
|
||||
return AppContext{}, err
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// LoadRecords will load records from file
|
||||
func (ctx *AppContext) LoadRecords(filename string) error {
|
||||
data, err := os.ReadFile(filename)
|
||||
func (ctx *AppContext) LoadRecords() error {
|
||||
data, err := os.ReadFile(ctx.dataPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -27,12 +37,12 @@ func (ctx *AppContext) LoadRecords(filename string) error {
|
||||
}
|
||||
|
||||
// SaveRecords will save records to a file
|
||||
func (ctx *AppContext) SaveRecords(filename string) error {
|
||||
func (ctx *AppContext) SaveRecords() error {
|
||||
jsonData, err := json.Marshal(ctx.Records)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(filename, jsonData, 0660)
|
||||
return os.WriteFile(ctx.dataPath, jsonData, 0660)
|
||||
}
|
||||
|
||||
// AddReading will add a Reading to the AppContext
|
||||
|
12
main.go
12
main.go
@ -9,6 +9,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"ketotrack/config"
|
||||
"ketotrack/data"
|
||||
"ketotrack/model"
|
||||
)
|
||||
@ -38,9 +39,14 @@ func init() {
|
||||
}
|
||||
|
||||
func main() {
|
||||
var appCtx data.AppContext
|
||||
appConfig := config.Load()
|
||||
appCtx, err := data.NewContext(appConfig.DataPath)
|
||||
if err != nil {
|
||||
fmt.Printf("Error initializing application context: %s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := appCtx.LoadRecords(recordsFilename); err != nil {
|
||||
if err := appCtx.LoadRecords(); err != nil {
|
||||
fmt.Printf("Error loading records from file: %s\n", err)
|
||||
}
|
||||
|
||||
@ -79,7 +85,7 @@ func main() {
|
||||
}
|
||||
|
||||
// Save Records before exiting
|
||||
if err := appCtx.SaveRecords(recordsFilename); err != nil {
|
||||
if err := appCtx.SaveRecords(); err != nil {
|
||||
fmt.Printf("Error saving records to file: %s\n", err)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user