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

package server
import "errors"
type User struct {
ID int64
Email string
Password string
}
type UserDB interface {
FindByID(id int64) (*User, error)
FindByEmail(email string) (*User, error)
Save(*User) error
}
type inMemoryUserDB struct {
UserDB
nextID int64
users []*User
}
func newInMemoryUserDB() *inMemoryUserDB {
return &inMemoryUserDB{
nextID: 1,
users: make([]*User, 0),
}
}
func (m *inMemoryUserDB) FindByID(id int64) (*User, error) {
for _, u := range m.users {
if u.ID == id {
return u, nil
}
}
return nil, errors.New("User not found.")
}
func (m *inMemoryUserDB) FindByEmail(email string) (*User, error) {
for _, u := range m.users {
if u.Email == email {
return u, nil
}
}
return nil, errors.New("User not found.")
}
func (m *inMemoryUserDB) Save(user *User) error {
for i, u := range m.users {
if u.ID == user.ID || u.Email == user.Email {
m.users[i] = user
return nil
}
}
user.ID = m.nextID
m.users = append(m.users, user)
m.nextID++
return nil
}