/
ivvlb
/
FirstRESRAPIOnGo
Обзор
Документация
Войти
/
ivvlb
/
FirstRESRAPIOnGo
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
storage.go
82 строки
1 KB
ivvlb1202
I've done this project (owO)
01 янв 2025, 16:30
01 янв 2025, 16:30
0d14245
Код
Авторство
О чём код?
package main import ( "fmt" "sync" ) type Employee struct { ID int `json:"id"` Name string `json:"name"` Sex string `json:"sex"` Age int `json:"age"` Salary int `json:"salary"` } type Storage interface { Insert(e *Employee) error Get(id int) (Employee, error) Update(e *Employee) error Delete(id int) error } type MemoryStorage struct { counter int data map[int]Employee sync.Mutex } // Update implements Storage. func (s *MemoryStorage) Update(e *Employee) error { s.Lock() defer s.Unlock() if _, exists := s.data[e.ID]; !exists { return fmt.Errorf("employee with id %d not found", e.ID) } s.data[e.ID] = *e return nil } func NewMemoryStorage() *MemoryStorage { return &MemoryStorage{ data: make(map[int]Employee), counter: 1, } } func (s *MemoryStorage) Insert(e *Employee) error { s.Lock() defer s.Unlock() e.ID = s.counter s.data[e.ID] = *e s.counter++ return nil } func (s *MemoryStorage) Delete(id int) error { s.Lock() defer s.Unlock() if _, exists := s.data[id]; !exists { return fmt.Errorf("employee with id %d not found", id) } delete(s.data, id) return nil } func (s *MemoryStorage) Get(id int) (Employee, error) { s.Lock() defer s.Unlock() employee, exists := s.data[id] if !exists { return Employee{}, fmt.Errorf("employee with id %d not found", id) } return employee, nil }