-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
79 lines (61 loc) · 1.69 KB
/
main.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"context"
"log"
"net"
"sync"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
pb "github.com/juanjcsr/opi_areainfluencia/proto/consignment"
)
const port = ":50051"
type repository interface {
Create(consignment *pb.Consignment) (*pb.Consignment, error)
GetAll() []*pb.Consignment
}
// Repository = simulates a datastore
type Repository struct {
mu sync.Mutex
consignments []*pb.Consignment
}
//Createe a new consignment
func (repo *Repository) Create(consignment *pb.Consignment) (*pb.Consignment, error) {
repo.mu.Lock()
updated := append(repo.consignments, consignment)
repo.consignments = updated
repo.mu.Unlock()
return consignment, nil
}
func (repo *Repository) GetAll() []*pb.Consignment {
return repo.consignments
}
//implements all of the methods to satisfy the service defined
// in the protobuf definition.
type service struct {
repo repository
}
func (s *service) CreateConsignment(ctx context.Context, req *pb.Consignment) (*pb.Response, error) {
consignment, err := s.repo.Create(req)
if err != nil {
return nil, err
}
return &pb.Response{Created: true, Consignment: consignment}, nil
}
func (s *service) GetConsignments(ctx context.Context, req *pb.GetRequest) (*pb.Response, error) {
consignments := s.repo.GetAll()
return &pb.Response{Consignments: consignments}, nil
}
func main() {
repo := &Repository{}
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterShippingServiceServer(s, &service{repo})
reflection.Register(s)
log.Println("running on port:", port)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}