package main import ( "encoding/json" "fmt" "os" "reflect" ) type FileSystemUserStore struct { database *json.Encoder userList UserList } func NewFileSystemUserStore(file *os.File) (*FileSystemUserStore, error) { err := initialiseUserDBFile(file) if err != nil { fmt.Errorf("problem initializing user db file, %v", err) } userList, err := NewUserList(file) if err != nil { return nil, fmt.Errorf("problem loading user list from file %s, %v", file.Name(), err) } return &FileSystemUserStore{ database: json.NewEncoder(&Tape{file}), userList: userList, }, nil } func initialiseUserDBFile(file *os.File) error { file.Seek(0, 0) info, err := file.Stat() if err != nil { return fmt.Errorf("problem getting file info from file %s, %v", file.Name(), err) } if info.Size() == 0 { file.Write([]byte("[]")) file.Seek(0, 0) } return nil } // todo add interface func (f *FileSystemUserStore) AddUserToUserList(user User) { f.userList = append(f.userList, user) } func (f *FileSystemUserStore) DeleteUserFromUserList(user User) { var userList []User for _, u := range f.userList { if !reflect.DeepEqual(u, user) { userList = append(userList, u) } } f.userList = userList } func (f *FileSystemUserStore) GetUsers() UserList { return f.userList } func (f *FileSystemUserStore) UpdateUserFromUserList(toUpdate, newState User) { user := f.userList.Find(toUpdate.Username) *user = newState }