You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.0 KiB

  1. package main
  2. import "errors"
  3. type User struct {
  4. ID int64
  5. Email string
  6. Password string
  7. }
  8. type UserDB interface {
  9. FindByID(id int64) (*User, error)
  10. FindByEmail(email string) (*User, error)
  11. Save(*User) error
  12. }
  13. type inMemoryUserDB struct {
  14. UserDB
  15. nextID int
  16. users []*User
  17. }
  18. func newInMemoryUserDB() *inMemoryUserDB {
  19. return &inMemoryUserDB{
  20. nextID: 1,
  21. users: make([]*User, 0),
  22. }
  23. }
  24. func (m *inMemoryUserDB) FindByID(id int64) (*User, error) {
  25. for _, u := range m.users {
  26. if u.ID == id {
  27. return u, nil
  28. }
  29. }
  30. return nil, errors.New("User not found.")
  31. }
  32. func (m *inMemoryUserDB) FindByEmail(email string) (*User, error) {
  33. for _, u := range m.users {
  34. if u.Email == email {
  35. return u, nil
  36. }
  37. }
  38. return nil, errors.New("User not found.")
  39. }
  40. func (m *inMemoryUserDB) Save(user *User) error {
  41. for i, u := range m.users {
  42. if u.ID == user.ID || u.Email == user.Email {
  43. m.users[i] = user
  44. return nil
  45. }
  46. }
  47. user.ID = m.nextID
  48. m.users = append(m.users, user)
  49. m.nextID++
  50. return nil
  51. }