-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
98 lines (79 loc) · 1.75 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
pb "gihyo/catalogue/proto/book"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
emptypb "google.golang.org/protobuf/types/known/emptypb"
)
type Book struct {
Id int
Title string
Author string
Price int
}
var (
book1 = Book{
Id: 1,
Title: "The Awakening",
Author: "Kate Chopin",
Price: 1000,
}
book2 = Book{
Id: 2,
Title: "City of Glass",
Author: "Paul Auster",
Price: 2000,
}
books = []Book{book1, book2}
)
func getBook(i int) Book {
return books[i-1]
}
type server struct {
pb.UnimplementedCatalogueServer
}
func (s *server) GetBook(ctx context.Context, in *pb.GetBookRequest) (*pb.GetBookResponse, error) {
book := getBook(int(in.Id))
protoBook := &pb.Book{
Id: int32(book.Id),
Title: book.Title,
Author: book.Author,
Price: int32(book.Price),
}
return &pb.GetBookResponse{Book: protoBook}, nil
}
func (s *server) ListBooks(ctx context.Context, in *emptypb.Empty) (*pb.ListBooksResponse, error) {
protoBooks := make([]*pb.Book, 0)
for _, book := range books {
protoBook := &pb.Book{
Id: int32(book.Id),
Title: book.Title,
Author: book.Author,
Price: int32(book.Price),
}
protoBooks = append(protoBooks, protoBook)
}
return &pb.ListBooksResponse{Books: protoBooks}, nil
}
var (
port = flag.Int("port", 50051, "The server port")
)
func main() {
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterCatalogueServer(s, &server{})
reflection.Register(s)
log.Printf("server listening at %v", lis.Addr())
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}