package main import ( "encoding/json" "errors" "fmt" "os" "sync" ) var ( ContactsFile = "contacts.json" ) type ( Contacts []Contact ContactsStore struct { sync.Mutex data map[int]Contact } ) func NewContactsStore() (*ContactsStore, error) { cs := ContactsStore{ data: make(map[int]Contact), } if err := cs.Load(); err != nil { return nil, err } return &cs, nil } func (cs *ContactsStore) Get(search string) Contacts { return make(Contacts, 0) } func (cs *ContactsStore) GetAll() Contacts { return make(Contacts, 0) } func (cs *ContactsStore) Load() error { if cs == nil { return errors.New("cannot load into nil store") } bs, err := os.ReadFile(ContactsFile) if err != nil { return fmt.Errorf("reading file: %w", err) } contacts := make(Contacts, 0) if err := json.Unmarshal(bs, &contacts); err != nil { return fmt.Errorf("unmarshalling file: %w", err) } cs.Lock() defer cs.Unlock() for _, contact := range contacts { cs.data[contact.ID] = contact } return nil } type Contact struct { ID int `json:"id"` First string `json:"first"` Last string `json:"last"` Phone string `json:"phone"` Email string `json:"email"` errors map[string]string }