-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpets.go
64 lines (49 loc) · 1.26 KB
/
pets.go
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
package server
import (
"context"
"github.com/golang-cz/gospeak/_examples/petStore/proto"
)
func (s *API) GetPet(ctx context.Context, ID int64) (pet *proto.Pet, err error) {
pet, ok := s.PetStore[ID]
if !ok {
return nil, proto.ErrorNotFound("pet(%v) not found", ID)
}
return pet, nil
}
func (s *API) ListPets(ctx context.Context) (pets []*proto.Pet, err error) {
pets = make([]*proto.Pet, 0, len(s.PetStore))
for _, pet := range s.PetStore {
pets = append(pets, pet)
}
return pets, nil
}
func (s *API) CreatePet(ctx context.Context, pet *proto.Pet) (*proto.Pet, error) {
if pet == nil {
return nil, proto.ErrorInvalidArgument("pet", "pet is required")
}
s.mu.Lock()
defer s.mu.Unlock()
pet.ID = s.SeqID
s.SeqID++
s.PetStore[pet.ID] = pet
return pet, nil
}
func (s *API) UpdatePet(ctx context.Context, ID int64, pet *proto.Pet) (*proto.Pet, error) {
if pet == nil {
return nil, proto.ErrorInvalidArgument("pet", "pet is required")
}
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.PetStore[pet.ID]
if !ok {
return nil, proto.ErrorNotFound("pet(%v) not found", ID)
}
s.PetStore[pet.ID] = pet
return pet, nil
}
func (s *API) DeletePet(ctx context.Context, ID int64) error {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.PetStore, ID)
return nil
}