1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
package storage
import (
"errors"
"fmt"
"net/http"
"github.com/manyminds/api2go"
"github.com/manyminds/api2go/examples/model"
)
// NewUserStorage initializes the storage
func NewUserStorage() *UserStorage {
return &UserStorage{make(map[string]*model.User), 1}
}
// UserStorage stores all users
type UserStorage struct {
users map[string]*model.User
idCount int
}
// GetAll returns the user map (because we need the ID as key too)
func (s UserStorage) GetAll() map[string]*model.User {
return s.users
}
// GetOne user
func (s UserStorage) GetOne(id string) (model.User, error) {
user, ok := s.users[id]
if ok {
return *user, nil
}
errMessage := fmt.Sprintf("User for id %s not found", id)
return model.User{}, api2go.NewHTTPError(errors.New(errMessage), errMessage, http.StatusNotFound)
}
// Insert a user
func (s *UserStorage) Insert(c model.User) string {
id := fmt.Sprintf("%d", s.idCount)
c.ID = id
s.users[id] = &c
s.idCount++
return id
}
// Delete one :(
func (s *UserStorage) Delete(id string) error {
_, exists := s.users[id]
if !exists {
return fmt.Errorf("User with id %s does not exist", id)
}
delete(s.users, id)
return nil
}
// Update a user
func (s *UserStorage) Update(c model.User) error {
_, exists := s.users[c.ID]
if !exists {
return fmt.Errorf("User with id %s does not exist", c.ID)
}
s.users[c.ID] = &c
return nil
}
|