From 20cf7bdb443c4146edf78bda9f8878287407a679 Mon Sep 17 00:00:00 2001 From: Carlosokumu Date: Thu, 29 Aug 2024 19:56:50 +0300 Subject: [PATCH] setup interface for file operations --- internal/utils/filehandler.go | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 internal/utils/filehandler.go diff --git a/internal/utils/filehandler.go b/internal/utils/filehandler.go new file mode 100644 index 0000000..9b768fd --- /dev/null +++ b/internal/utils/filehandler.go @@ -0,0 +1,50 @@ +package utils + +import ( + "encoding/json" + "os" +) + + +type AccountFileHandlerInterface interface { + EnsureFileExists() error + ReadAccountData() (map[string]string, error) + WriteAccountData(data map[string]string) error +} + + + +type AccountFileHandler2 struct { + FilePath string +} + +// Implement the methods required by AccountFileHandlerInterface. +func (afh *AccountFileHandler2) EnsureFileExists() error { + f, err := os.OpenFile(afh.FilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return err + } + return f.Close() +} +func (afh *AccountFileHandler2) ReadAccountData() (map[string]string, error) { + jsonData, err := os.ReadFile(afh.FilePath) + if err != nil { + return nil, err + } + + var accountData map[string]string + err = json.Unmarshal(jsonData, &accountData) + if err != nil { + return nil, err + } + + return accountData, nil +} +func (afh *AccountFileHandler2) WriteAccountData(data map[string]string) error { + jsonData, err := json.Marshal(data) + if err != nil { + return err + } + + return os.WriteFile(afh.FilePath, jsonData, 0644) +} \ No newline at end of file